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 |
---|---|---|---|---|---|---|
pragma solidity ^0.4.24;
import "./libraries/SafeMath.sol";
import "./interfaces/ERC20_Interface.sol";
/**
*Exchange creates an exchange for the swaps.
*/
contract Exchange{
using SafeMath for uint256;
/*Variables*/
/*Structs*/
//This is the base data structure for an order (the maker of the order and the price)
struct Order {
address maker;// the placer of the order
uint price;// The price in wei
uint amount;
address asset;
}
struct ListAsset {
uint price;
uint amount;
bool isLong;
}
//order_nonce;
uint internal order_nonce;
address public owner; //The owner of the market contract
address[] public openDdaListAssets;
//Index telling where a specific tokenId is in the forSale array
address[] public openBooks;
mapping (address => uint) public openDdaListIndex;
mapping(address => mapping (address => uint)) public totalListed;//user to tokenamounts
mapping(address => ListAsset) public listOfAssets;
//Maps an OrderID to the list of orders
mapping(uint256 => Order) public orders;
//An mapping of a token address to the orderID's
mapping(address => uint256[]) public forSale;
//Index telling where a specific tokenId is in the forSale array
mapping(uint256 => uint256) internal forSaleIndex;
//mapping of address to position in openBooks
mapping (address => uint) internal openBookIndex;
//mapping of user to their orders
mapping(address => uint[]) public userOrders;
//mapping from orderId to userOrder position
mapping(uint => uint) internal userOrderIndex;
//A list of the blacklisted addresses
mapping(address => bool) internal blacklist;
/*Events*/
event ListDDA(address _token, uint256 _amount, uint256 _price,bool _isLong);
event BuyDDA(address _token,address _sender, uint256 _amount, uint256 _price);
event UnlistDDA(address _token);
event OrderPlaced(uint _orderID, address _sender,address _token, uint256 _amount, uint256 _price);
event Sale(uint _orderID,address _sender,address _token, uint256 _amount, uint256 _price);
event OrderRemoved(uint _orderID,address _sender,address _token, uint256 _amount, uint256 _price);
/*Modifiers*/
/**
*@dev Access modifier for Owner functionality
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/*Functions*/
/**
*@dev the constructor argument to set the owner and initialize the array.
*/
constructor() public{
owner = msg.sender;
openBooks.push(address(0));
order_nonce = 1;
}
/**
*@dev list allows a party to place an order on the orderbook
*@param _tokenadd address of the drct tokens
*@param _amount number of DRCT tokens
*@param _price uint256 price of all tokens in wei
*/
function list(address _tokenadd, uint256 _amount, uint256 _price) external {
require(blacklist[msg.sender] == false);
require(_price > 0);
ERC20_Interface token = ERC20_Interface(_tokenadd);
require(totalListed[msg.sender][_tokenadd] + _amount <= token.allowance(msg.sender,address(this)));
if(forSale[_tokenadd].length == 0){
forSale[_tokenadd].push(0);
}
forSaleIndex[order_nonce] = forSale[_tokenadd].length;
forSale[_tokenadd].push(order_nonce);
orders[order_nonce] = Order({
maker: msg.sender,
asset: _tokenadd,
price: _price,
amount:_amount
});
emit OrderPlaced(order_nonce,msg.sender,_tokenadd,_amount,_price);
if(openBookIndex[_tokenadd] == 0 ){
openBookIndex[_tokenadd] = openBooks.length;
openBooks.push(_tokenadd);
}
userOrderIndex[order_nonce] = userOrders[msg.sender].length;
userOrders[msg.sender].push(order_nonce);
totalListed[msg.sender][_tokenadd] += _amount;
order_nonce += 1;
}
/**
*@dev list allows DDA to list an order
*@param _asset address
*@param _amount of asset
*@param _price uint256 price per unit in wei
*@param _isLong true if it is long
*/
//Then you would have a mapping from an asset to its price/ quantity when you list it.
function listDda(address _asset, uint256 _amount, uint256 _price, bool _isLong) public onlyOwner() {
require(blacklist[msg.sender] == false);
ListAsset storage listing = listOfAssets[_asset];
listing.price = _price;
listing.amount= _amount;
listing.isLong= _isLong;
openDdaListIndex[_asset] = openDdaListAssets.length;
openDdaListAssets.push(_asset);
emit ListDDA(_asset,_amount,_price,_isLong);
}
/**
*@dev list allows a DDA to remove asset
*@param _asset address
*/
function unlistDda(address _asset) public onlyOwner() {
require(blacklist[msg.sender] == false);
uint256 indexToDelete;
uint256 lastAcctIndex;
address lastAdd;
ListAsset storage listing = listOfAssets[_asset];
listing.price = 0;
listing.amount= 0;
listing.isLong= false;
indexToDelete = openDdaListIndex[_asset];
lastAcctIndex = openDdaListAssets.length.sub(1);
lastAdd = openDdaListAssets[lastAcctIndex];
openDdaListAssets[indexToDelete]=lastAdd;
openDdaListIndex[lastAdd]= indexToDelete;
openDdaListAssets.length--;
openDdaListIndex[_asset] = 0;
emit UnlistDDA(_asset);
}
/**
*@dev buy allows a party to partially fill an order
*@param _asset is the address of the assset listed
*@param _amount is the amount of tokens to buy
*/
function buyPerUnit(address _asset, uint256 _amount) external payable {
require(blacklist[msg.sender] == false);
ListAsset storage listing = listOfAssets[_asset];
require(_amount <= listing.amount);
uint totalPrice = _amount.mul(listing.price);
require(msg.value == totalPrice);
ERC20_Interface token = ERC20_Interface(_asset);
if(token.allowance(owner,address(this)) >= _amount){
assert(token.transferFrom(owner,msg.sender, _amount));
owner.transfer(totalPrice);
listing.amount= listing.amount.sub(_amount);
}
emit BuyDDA(_asset,msg.sender,_amount,totalPrice);
}
/**
*@dev unlist allows a party to remove their order from the orderbook
*@param _orderId is the uint256 ID of order
*/
function unlist(uint256 _orderId) external{
require(forSaleIndex[_orderId] > 0);
Order memory _order = orders[_orderId];
require(msg.sender== _order.maker || msg.sender == owner);
unLister(_orderId,_order);
emit OrderRemoved(_orderId,msg.sender,_order.asset,_order.amount,_order.price);
}
/**
*@dev buy allows a party to fill an order
*@param _orderId is the uint256 ID of order
*/
function buy(uint256 _orderId) external payable {
Order memory _order = orders[_orderId];
require(_order.price != 0 && _order.maker != address(0) && _order.asset != address(0) && _order.amount != 0);
require(msg.value == _order.price);
require(blacklist[msg.sender] == false);
address maker = _order.maker;
ERC20_Interface token = ERC20_Interface(_order.asset);
if(token.allowance(_order.maker,address(this)) >= _order.amount){
assert(token.transferFrom(_order.maker,msg.sender, _order.amount));
maker.transfer(_order.price);
}
unLister(_orderId,_order);
emit Sale(_orderId,msg.sender,_order.asset,_order.amount,_order.price);
}
/**
*@dev getOrder lists the price,amount, and maker of a specific token for a sale
*@param _orderId uint256 ID of order
*@return address of the party selling
*@return uint of the price of the sale (in wei)
*@return uint of the order amount of the sale
*@return address of the token
*/
function getOrder(uint256 _orderId) external view returns(address,uint,uint,address){
Order storage _order = orders[_orderId];
return (_order.maker,_order.price,_order.amount,_order.asset);
}
/**
*@dev allows the owner to change who the owner is
*@param _owner is the address of the new owner
*/
function setOwner(address _owner) public onlyOwner() {
owner = _owner;
}
/**
*@notice This allows the owner to stop a malicious party from spamming the orderbook
*@dev Allows the owner to blacklist addresses from using this exchange
*@param _address the address of the party to blacklist
*@param _motion true or false depending on if blacklisting or not
*/
function blacklistParty(address _address, bool _motion) public onlyOwner() {
blacklist[_address] = _motion;
}
/**
*@dev Allows parties to see if one is blacklisted
*@param _address the address of the party to blacklist
*@return bool true for is blacklisted
*/
function isBlacklist(address _address) public view returns(bool) {
return blacklist[_address];
}
/**
*@dev getOrderCount allows parties to query how many orders are on the book
*@param _token address used to count the number of orders
*@return _uint of the number of orders in the orderbook
*/
function getOrderCount(address _token) public constant returns(uint) {
return forSale[_token].length;
}
/**
*@dev Gets number of open orderbooks
*@return _uint of the number of tokens with open orders
*/
function getBookCount() public constant returns(uint) {
return openBooks.length;
}
/**
*@dev getOrders allows parties to get an array of all orderId's open for a given token
*@param _token address of the drct token
*@return _uint[] an array of the orders in the orderbook
*/
function getOrders(address _token) public constant returns(uint[]) {
return forSale[_token];
}
/**
*@dev getUserOrders allows parties to get an array of all orderId's open for a given user
*@param _user address
*@return _uint[] an array of the orders in the orderbook for the user
*/
function getUserOrders(address _user) public constant returns(uint[]) {
return userOrders[_user];
}
/**
*@dev getter function to get all openDdaListAssets
*/
function getopenDdaListAssets() view public returns (address[]){
return openDdaListAssets;
}
/**
*@dev Gets the DDA List Asset information for the specifed
*asset address
*@param _assetAddress for DDA list
*@return price, amount and true if isLong
*/
function getDdaListAssetInfo(address _assetAddress) public view returns(uint, uint, bool){
return(listOfAssets[_assetAddress].price,listOfAssets[_assetAddress].amount,listOfAssets[_assetAddress].isLong);
}
/**
*@param _owner address
*@param _asset address
*@return Returns the total listed the owner has listed for the specified asset
*/
function getTotalListed(address _owner, address _asset) public view returns (uint) {
return totalListed[_owner][_asset];
}
/**
*@dev An internal function to update mappings when an order is removed from the book
*@param _orderId is the uint256 ID of order
*@param _order is the struct containing the details of the order
*/
function unLister(uint256 _orderId, Order _order) internal{
uint256 tokenIndex;
uint256 lastTokenIndex;
address lastAdd;
uint256 lastToken;
totalListed[_order.maker][_order.asset] -= _order.amount;
if(forSale[_order.asset].length == 2){
tokenIndex = openBookIndex[_order.asset];
lastTokenIndex = openBooks.length.sub(1);
lastAdd = openBooks[lastTokenIndex];
openBooks[tokenIndex] = lastAdd;
openBookIndex[lastAdd] = tokenIndex;
openBooks.length--;
openBookIndex[_order.asset] = 0;
forSale[_order.asset].length -= 2;
}
else{
tokenIndex = forSaleIndex[_orderId];
lastTokenIndex = forSale[_order.asset].length.sub(1);
lastToken = forSale[_order.asset][lastTokenIndex];
forSale[_order.asset][tokenIndex] = lastToken;
forSaleIndex[lastToken] = tokenIndex;
forSale[_order.asset].length--;
}
forSaleIndex[_orderId] = 0;
orders[_orderId] = Order({
maker: address(0),
price: 0,
amount:0,
asset: address(0)
});
if(userOrders[_order.maker].length > 1){
tokenIndex = userOrderIndex[_orderId];
lastTokenIndex = userOrders[_order.maker].length.sub(1);
lastToken = userOrders[_order.maker][lastTokenIndex];
userOrders[_order.maker][tokenIndex] = lastToken;
userOrderIndex[lastToken] = tokenIndex;
}
userOrders[_order.maker].length--;
userOrderIndex[_orderId] = 0;
}
}
| *@dev Gets the DDA List Asset information for the specifedasset address@param _assetAddress for DDA list@return price, amount and true if isLong/ | function getDdaListAssetInfo(address _assetAddress) public view returns(uint, uint, bool){
return(listOfAssets[_assetAddress].price,listOfAssets[_assetAddress].amount,listOfAssets[_assetAddress].isLong);
}
| 7,273,040 | [
1,
3002,
326,
463,
9793,
987,
10494,
1779,
364,
326,
857,
430,
329,
9406,
1758,
389,
9406,
1887,
364,
463,
9793,
666,
2463,
6205,
16,
3844,
471,
638,
309,
353,
3708,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2343,
2414,
682,
6672,
966,
12,
2867,
389,
9406,
1887,
13,
1071,
1476,
1135,
12,
11890,
16,
2254,
16,
1426,
15329,
203,
3639,
327,
12,
1098,
951,
10726,
63,
67,
9406,
1887,
8009,
8694,
16,
1098,
951,
10726,
63,
67,
9406,
1887,
8009,
8949,
16,
1098,
951,
10726,
63,
67,
9406,
1887,
8009,
291,
3708,
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
] |
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./VotingBooth.sol";
import "../../../interfaces/IBean.sol";
import "../../../libraries/LibInternal.sol";
import "../../../libraries/LibIncentive.sol";
/**
* @author Publius
* @title Governance handles propsing, voting for and committing BIPs as well as pausing/unpausing.
**/
contract GovernanceFacet is VotingBooth {
using SafeMath for uint256;
using LibSafeMath32 for uint32;
using Decimal for Decimal.D256;
event Proposal(address indexed account, uint32 indexed bip, uint256 indexed start, uint256 period);
event VoteList(address indexed account, uint32[] bips, bool[] votes, uint256 roots);
event Unvote(address indexed account, uint32 indexed bip, uint256 roots);
event Commit(address indexed account, uint32 indexed bip);
event Incentivization(address indexed account, uint256 beans);
event Pause(address account, uint256 timestamp);
event Unpause(address account, uint256 timestamp, uint256 timePassed);
/**
* Proposition
**/
function propose(
IDiamondCut.FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata,
uint8 _pauseOrUnpause
)
external
{
require(canPropose(msg.sender), "Governance: Not enough Stalk.");
require(notTooProposed(msg.sender), "Governance: Too many active BIPs.");
require(
_init != address(0) || _diamondCut.length > 0 || _pauseOrUnpause > 0,
"Governance: Proposition is empty."
);
uint32 bipId = createBip(
_diamondCut,
_init,
_calldata,
_pauseOrUnpause,
C.getGovernancePeriod(),
msg.sender
);
s.a[msg.sender].proposedUntil = startFor(bipId).add(periodFor(bipId));
emit Proposal(msg.sender, bipId, season(), C.getGovernancePeriod());
_vote(msg.sender, bipId);
}
/**
* Voting
**/
function vote(uint32 bip) external {
require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk.");
require(isNominated(bip), "Governance: Not nominated.");
require(isActive(bip), "Governance: Ended.");
require(!voted(msg.sender, bip), "Governance: Already voted.");
_vote(msg.sender, bip);
}
/// @notice Takes in a list of multiple bips and performs a vote on all of them
/// @param bip_list Contains the bip proposal ids to vote on
function voteAll(uint32[] calldata bip_list) external {
require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk.");
bool[] memory vote_types = new bool[](bip_list.length);
uint i = 0;
uint32 lock = s.a[msg.sender].votedUntil;
for (i = 0; i < bip_list.length; i++) {
uint32 bip = bip_list[i];
require(isNominated(bip), "Governance: Not nominated.");
require(isActive(bip), "Governance: Ended.");
require(!voted(msg.sender, bip), "Governance: Already voted.");
recordVote(msg.sender, bip);
vote_types[i] = true;
// Place timelocks
uint32 newLock = startFor(bip).add(periodFor(bip));
if (newLock > lock) lock = newLock;
}
s.a[msg.sender].votedUntil = lock;
emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender));
}
function unvote(uint32 bip) external {
require(isNominated(bip), "Governance: Not nominated.");
require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk.");
require(isActive(bip), "Governance: Ended.");
require(voted(msg.sender, bip), "Governance: Not voted.");
require(proposer(bip) != msg.sender, "Governance: Is proposer.");
unrecordVote(msg.sender, bip);
updateVotedUntil(msg.sender);
emit Unvote(msg.sender, bip, balanceOfRoots(msg.sender));
}
/// @notice Takes in a list of multiple bips and performs an unvote on all of them
/// @param bip_list Contains the bip proposal ids to unvote on
function unvoteAll(uint32[] calldata bip_list) external {
require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk.");
uint i = 0;
bool[] memory vote_types = new bool[](bip_list.length);
for (i = 0; i < bip_list.length; i++) {
uint32 bip = bip_list[i];
require(isNominated(bip), "Governance: Not nominated.");
require(isActive(bip), "Governance: Ended.");
require(voted(msg.sender, bip), "Governance: Not voted.");
require(proposer(bip) != msg.sender, "Governance: Is proposer.");
unrecordVote(msg.sender, bip);
vote_types[i] = false;
}
updateVotedUntil(msg.sender);
emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender));
}
/// @notice Takes in a list of multiple bips and performs a vote or unvote on all of them
/// depending on their status: whether they are currently voted on or not voted on
/// @param bip_list Contains the bip proposal ids
function voteUnvoteAll(uint32[] calldata bip_list) external {
require(balanceOfRoots(msg.sender) > 0, "Governance: Must have Stalk.");
uint i = 0;
bool[] memory vote_types = new bool[](bip_list.length);
for (i = 0; i < bip_list.length; i++) {
uint32 bip = bip_list[i];
require(isNominated(bip), "Governance: Not nominated.");
require(isActive(bip), "Governance: Ended.");
if (s.g.voted[bip][msg.sender]) {
// Handle Unvote
require(proposer(bip) != msg.sender, "Governance: Is proposer.");
unrecordVote(msg.sender, bip);
vote_types[i] = false;
} else {
// Handle Vote
recordVote(msg.sender, bip);
vote_types[i] = true;
}
}
updateVotedUntil(msg.sender);
emit VoteList(msg.sender, bip_list, vote_types, balanceOfRoots(msg.sender));
}
/**
* Execution
**/
function commit(uint32 bip) external {
require(isNominated(bip), "Governance: Not nominated.");
require(!isActive(bip), "Governance: Not ended.");
require(!isExpired(bip), "Governance: Expired.");
require(
endedBipVotePercent(bip).greaterThanOrEqualTo(C.getGovernancePassThreshold()),
"Governance: Must have majority."
);
_execute(msg.sender, bip, true, true);
}
function emergencyCommit(uint32 bip) external {
require(isNominated(bip), "Governance: Not nominated.");
require(
block.timestamp >= timestamp(bip).add(C.getGovernanceEmergencyPeriod()),
"Governance: Too early.");
require(isActive(bip), "Governance: Ended.");
require(
bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()),
"Governance: Must have super majority."
);
_execute(msg.sender, bip, false, true);
}
function pauseOrUnpause(uint32 bip) external {
require(isNominated(bip), "Governance: Not nominated.");
require(diamondCutIsEmpty(bip),"Governance: Has diamond cut.");
require(isActive(bip), "Governance: Ended.");
require(
bipVotePercent(bip).greaterThanOrEqualTo(C.getGovernanceEmergencyThreshold()),
"Governance: Must have super majority."
);
_execute(msg.sender, bip, false, false);
}
function _execute(address account, uint32 bip, bool ended, bool cut) private {
if (!ended) endBip(bip);
s.g.bips[bip].executed = true;
if (cut) cutBip(bip);
pauseOrUnpauseBip(bip);
incentivize(account, ended, bip, C.getCommitIncentive());
emit Commit(account, bip);
}
function incentivize(address account, bool compound, uint32 bipId, uint256 amount) private {
if (compound) amount = LibIncentive.fracExp(amount, 100, incentiveTime(bipId), 2);
IBean(s.c.bean).mint(account, amount);
emit Incentivization(account, amount);
}
/**
* Pause / Unpause
**/
function ownerPause() external {
LibDiamond.enforceIsContractOwner();
pause();
}
function ownerUnpause() external {
LibDiamond.enforceIsContractOwner();
unpause();
}
function pause() private {
if (s.paused) return;
s.paused = true;
s.o.initialized = false;
s.pausedAt = uint128(block.timestamp);
emit Pause(msg.sender, block.timestamp);
}
function unpause() private {
if (!s.paused) return;
s.paused = false;
uint256 timePassed = block.timestamp.sub(uint(s.pausedAt));
timePassed = (timePassed.div(3600).add(1)).mul(3600);
s.season.start = s.season.start.add(timePassed);
emit Unpause(msg.sender, block.timestamp, timePassed);
}
function pauseOrUnpauseBip(uint32 bipId) private {
if (s.g.bips[bipId].pauseOrUnpause == 1) pause();
else if (s.g.bips[bipId].pauseOrUnpause == 2) unpause();
}
}
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import './Bip.sol';
/**
* @author Publius
* @title Voting Booth
**/
contract VotingBooth is Bip {
using SafeMath for uint256;
using LibSafeMath32 for uint32;
event Vote(address indexed account, uint32 indexed bip, uint256 roots);
/**
* Voting
**/
function _vote(address account, uint32 bipId) internal {
recordVote(account, bipId);
placeVotedUntil(account, bipId);
emit Vote(account, bipId, balanceOfRoots(account));
}
function recordVote(address account, uint32 bipId) internal {
s.g.voted[bipId][account] = true;
s.g.bips[bipId].roots = s.g.bips[bipId].roots.add(balanceOfRoots(account));
}
function unrecordVote(address account, uint32 bipId) internal {
s.g.voted[bipId][account] = false;
s.g.bips[bipId].roots = s.g.bips[bipId].roots.sub(balanceOfRoots(account));
}
function placeVotedUntil(address account, uint32 bipId) internal {
uint32 newLock = startFor(bipId).add(periodFor(bipId));
if (newLock > s.a[account].votedUntil) {
s.a[account].votedUntil = newLock;
}
}
function updateVotedUntil(address account) internal {
uint32[] memory actives = activeBips();
uint32 lastSeason = 0;
for (uint256 i = 0; i < actives.length; i++) {
uint32 activeBip = actives[i];
if (s.g.voted[activeBip][account]) {
uint32 bipEnd = startFor(activeBip).add(periodFor(activeBip));
if (bipEnd > lastSeason) lastSeason = bipEnd;
}
}
s.a[account].votedUntil = lastSeason;
}
}
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @author Publius
* @title Bean Interface
**/
abstract contract IBean is IERC20 {
function burn(uint256 amount) public virtual;
function burnFrom(address account, uint256 amount) public virtual;
function mint(address account, uint256 amount) public virtual returns (bool);
}
/*
SPDX-License-Identifier: MIT
*/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/**
* @author Publius
* @title Internal Library handles gas efficient function calls between facets.
**/
interface ISiloUpdate {
function updateSilo(address account) external payable;
}
library LibInternal {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint16 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint16 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
address[] facetAddresses;
mapping(bytes4 => bool) supportedInterfaces;
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
function updateSilo(address account) internal {
DiamondStorage storage ds = diamondStorage();
address facet = ds.selectorToFacetAndPosition[ISiloUpdate.updateSilo.selector].facetAddress;
bytes memory myFunctionCall = abi.encodeWithSelector(ISiloUpdate.updateSilo.selector, account);
(bool success,) = address(facet).delegatecall(myFunctionCall);
require(success, "Silo: updateSilo failed.");
}
}
/*
SPDX-License-Identifier: MIT
*/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/**
* @author Publius
* @title Incentive Library calculates the exponential incentive rewards efficiently.
**/
library LibIncentive {
/// @notice fracExp estimates an exponential expression in the form: k * (1 + 1/q) ^ N.
/// We use a binomial expansion to estimate the exponent to avoid running into integer overflow issues.
/// @param k - the principle amount
/// @param q - the base of the fraction being exponentiated
/// @param n - the exponent
/// @param x - the excess # of times to run the iteration.
/// @return s - the solution to the exponential equation
function fracExp(uint k, uint q, uint n, uint x) internal pure returns (uint s) {
// The upper bound in which the binomial expansion is expected to converge
// Upon testing with a limit of n <= 300, x = 2, k = 100, q = 100 (parameters Beanstalk currently uses)
// we found this p optimizes for gas and error
uint p = log_two(n) + 1 + x * n / q;
// Solution for binomial expansion in Solidity.
// Motivation: https://ethereum.stackexchange.com/questions/10425
uint N = 1;
uint B = 1;
for (uint i = 0; i < p; ++i){
s += k * N / B / (q**i);
N = N * (n-i);
B = B * (i+1);
}
}
/// @notice log_two calculates the log2 solution in a gas efficient manner
/// Motivation: https://ethereum.stackexchange.com/questions/8086
/// @param x - the base to calculate log2 of
function log_two(uint x) private pure returns (uint y) {
assembly {
let arg := x
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)))
}
}
}
/**
* SPDX-License-Identifier: MIT
**/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../libraries/LibSafeMath32.sol";
import "../../AppStorage.sol";
import "../../../C.sol";
import "../../../libraries/Decimal.sol";
import "../../../libraries/LibDiamond.sol";
/**
* @author Publius
* @title BIP
**/
contract Bip {
AppStorage internal s;
using SafeMath for uint256;
using LibSafeMath32 for uint32;
using Decimal for Decimal.D256;
/**
* Getters
**/
// Bips
function activeBips() public view returns (uint32[] memory) {
return s.g.activeBips;
}
function numberOfBips() public view returns (uint32) {
return s.g.bipIndex;
}
function bip(uint32 bipId) public view returns (Storage.Bip memory) {
return s.g.bips[bipId];
}
function voted(address account, uint32 bipId) public view returns (bool) {
return s.g.voted[bipId][account];
}
function rootsFor(uint32 bipId) public view returns (uint256) {
return s.g.bips[bipId].roots;
}
// Diamond Cut
function bipDiamondCut(uint32 bipId) public view returns (Storage.DiamondCut memory) {
return s.g.diamondCuts[bipId];
}
function bipFacetCuts(uint32 bipId) public view returns (IDiamondCut.FacetCut[] memory) {
return s.g.diamondCuts[bipId].diamondCut;
}
function diamondCutIsEmpty(uint32 bipId) internal view returns (bool) {
return (
s.g.diamondCuts[bipId].diamondCut.length == 0 &&
s.g.diamondCuts[bipId].initAddress == address(0)
);
}
/**
* Internal
**/
// Bip Actions
function createBip(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata,
uint8 pauseOrUnpause,
uint32 period,
address account
)
internal
returns (uint32)
{
require(_init != address(0) || _calldata.length == 0, "Governance: calldata not empty.");
uint32 bipId = s.g.bipIndex;
s.g.bipIndex += 1;
s.g.bips[bipId].start = season();
s.g.bips[bipId].period = period;
s.g.bips[bipId].timestamp = uint128(block.timestamp);
s.g.bips[bipId].proposer = account;
s.g.bips[bipId].pauseOrUnpause = pauseOrUnpause;
for (uint i = 0; i < _diamondCut.length; i++)
s.g.diamondCuts[bipId].diamondCut.push(_diamondCut[i]);
s.g.diamondCuts[bipId].initAddress = _init;
s.g.diamondCuts[bipId].initData = _calldata;
s.g.activeBips.push(bipId);
return bipId;
}
function endBip(uint32 bipId) internal {
uint256 i = 0;
while(s.g.activeBips[i] != bipId) i++;
s.g.bips[bipId].timestamp = uint128(block.timestamp);
s.g.bips[bipId].endTotalRoots = totalRoots();
uint256 numberOfActiveBips = s.g.activeBips.length-1;
if (i < numberOfActiveBips) s.g.activeBips[i] = s.g.activeBips[numberOfActiveBips];
s.g.activeBips.pop();
}
function cutBip(uint32 bipId) internal {
if (diamondCutIsEmpty(bipId)) return;
LibDiamond.diamondCut(
s.g.diamondCuts[bipId].diamondCut,
s.g.diamondCuts[bipId].initAddress,
s.g.diamondCuts[bipId].initData
);
}
function proposer(uint32 bipId) internal view returns (address) {
return s.g.bips[bipId].proposer;
}
function startFor(uint32 bipId) internal view returns (uint32) {
return s.g.bips[bipId].start;
}
function periodFor(uint32 bipId) internal view returns (uint32) {
return s.g.bips[bipId].period;
}
function timestamp(uint32 bipId) internal view returns (uint256) {
return uint256(s.g.bips[bipId].timestamp);
}
function isNominated(uint32 bipId) internal view returns (bool) {
return startFor(bipId) > 0 && !s.g.bips[bipId].executed;
}
function isActive(uint32 bipId) internal view returns (bool) {
return season() < startFor(bipId).add(periodFor(bipId));
}
function isExpired(uint32 bipId) internal view returns (bool) {
return season() > startFor(bipId).add(periodFor(bipId)).add(C.getGovernanceExpiration());
}
function bipVotePercent(uint32 bipId) internal view returns (Decimal.D256 memory) {
return Decimal.ratio(rootsFor(bipId), totalRoots());
}
function endedBipVotePercent(uint32 bipId) internal view returns (Decimal.D256 memory) {
return Decimal.ratio(s.g.bips[bipId].roots,s.g.bips[bipId].endTotalRoots);
}
// Bip Proposition
function canPropose(address account) internal view returns (bool) {
if (totalRoots() == 0 || balanceOfRoots(account) == 0) {
return false;
}
Decimal.D256 memory stake = Decimal.ratio(balanceOfRoots(account), totalRoots());
return stake.greaterThan(C.getGovernanceProposalThreshold());
}
function notTooProposed(address account) internal view returns (bool) {
uint256 propositions;
for (uint256 i = 0; i < s.g.activeBips.length; i++) {
uint32 bipId = s.g.activeBips[i];
if (s.g.bips[bipId].proposer == account) propositions += 1;
}
return (propositions < C.getMaxPropositions());
}
/**
* Shed
**/
function incentiveTime(uint32 bipId) internal view returns (uint256) {
uint256 time = block.timestamp.sub(s.g.bips[bipId].timestamp);
if (time > 1800) time = 1800;
return time / 6;
}
function balanceOfRoots(address account) internal view returns (uint256) {
return s.a[account].roots;
}
function totalRoots() internal view returns (uint256) {
return s.s.roots;
}
function season() internal view returns (uint32) { return s.season.current; }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @author Publius
* @title LibSafeMath32 is a uint32 variation of Open Zeppelin's Safe Math library.
**/
library LibSafeMath32 {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint32 a, uint32 b) internal pure returns (bool, uint32) {
uint32 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(uint32 a, uint32 b) internal pure returns (bool, uint32) {
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(uint32 a, uint32 b) internal pure returns (bool, uint32) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint32 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(uint32 a, uint32 b) internal pure returns (bool, uint32) {
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(uint32 a, uint32 b) internal pure returns (bool, uint32) {
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(uint32 a, uint32 b) internal pure returns (uint32) {
uint32 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint32 a, uint32 b) internal pure returns (uint32) {
require(b <= a, "SafeMath: subtraction overflow");
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(uint32 a, uint32 b) internal pure returns (uint32) {
if (a == 0) return 0;
uint32 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, 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(uint32 a, uint32 b) internal pure returns (uint32) {
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(uint32 a, uint32 b) internal pure returns (uint32) {
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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
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(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) {
require(b > 0, errorMessage);
return a % b;
}
}
/*
SPDX-License-Identifier: MIT
*/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "../interfaces/IDiamondCut.sol";
/**
* @author Publius
* @title App Storage defines the state object for Beanstalk.
**/
contract Account {
struct Field {
mapping(uint256 => uint256) plots;
mapping(address => uint256) podAllowances;
}
struct AssetSilo {
mapping(uint32 => uint256) withdrawals;
mapping(uint32 => uint256) deposits;
mapping(uint32 => uint256) depositSeeds;
}
struct Deposit {
uint128 amount;
uint128 bdv;
}
struct Silo {
uint256 stalk;
uint256 seeds;
}
struct SeasonOfPlenty {
uint256 base;
uint256 roots;
uint256 basePerRoot;
}
struct State {
Field field;
AssetSilo bean;
AssetSilo lp;
Silo s;
uint32 votedUntil;
uint32 lastUpdate;
uint32 lastSop;
uint32 lastRain;
uint32 lastSIs;
uint32 proposedUntil;
SeasonOfPlenty sop;
uint256 roots;
uint256 wrappedBeans;
mapping(address => mapping(uint32 => Deposit)) deposits;
mapping(address => mapping(uint32 => uint256)) withdrawals;
}
}
contract Storage {
struct Contracts {
address bean;
address pair;
address pegPair;
address weth;
}
// Field
struct Field {
uint256 soil;
uint256 pods;
uint256 harvested;
uint256 harvestable;
}
// Governance
struct Bip {
address proposer;
uint32 start;
uint32 period;
bool executed;
int pauseOrUnpause;
uint128 timestamp;
uint256 roots;
uint256 endTotalRoots;
}
struct DiamondCut {
IDiamondCut.FacetCut[] diamondCut;
address initAddress;
bytes initData;
}
struct Governance {
uint32[] activeBips;
uint32 bipIndex;
mapping(uint32 => DiamondCut) diamondCuts;
mapping(uint32 => mapping(address => bool)) voted;
mapping(uint32 => Bip) bips;
}
// Silo
struct AssetSilo {
uint256 deposited;
uint256 withdrawn;
}
struct IncreaseSilo {
uint256 beans;
uint256 stalk;
}
struct V1IncreaseSilo {
uint256 beans;
uint256 stalk;
uint256 roots;
}
struct SeasonOfPlenty {
uint256 weth;
uint256 base;
uint32 last;
}
struct Silo {
uint256 stalk;
uint256 seeds;
uint256 roots;
}
// Season
struct Oracle {
bool initialized;
uint256 cumulative;
uint256 pegCumulative;
uint32 timestamp;
uint32 pegTimestamp;
}
struct Rain {
uint32 start;
bool raining;
uint256 pods;
uint256 roots;
}
struct Season {
uint32 current;
uint32 sis;
uint8 withdrawSeasons;
uint256 start;
uint256 period;
uint256 timestamp;
}
struct Weather {
uint256 startSoil;
uint256 lastDSoil;
uint96 lastSoilPercent;
uint32 lastSowTime;
uint32 nextSowTime;
uint32 yield;
bool didSowBelowMin;
bool didSowFaster;
}
struct Fundraiser {
address payee;
address token;
uint256 total;
uint256 remaining;
uint256 start;
}
struct SiloSettings {
bytes4 selector;
uint32 seeds;
uint32 stalk;
}
}
struct AppStorage {
uint8 index;
int8[32] cases;
bool paused;
uint128 pausedAt;
Storage.Season season;
Storage.Contracts c;
Storage.Field f;
Storage.Governance g;
Storage.Oracle o;
Storage.Rain r;
Storage.Silo s;
uint256 reentrantStatus; // An intra-transaction state variable to protect against reentrance
Storage.Weather w;
Storage.AssetSilo bean;
Storage.AssetSilo lp;
Storage.IncreaseSilo si;
Storage.SeasonOfPlenty sop;
Storage.V1IncreaseSilo v1SI;
uint256 unclaimedRoots;
uint256 v2SIBeans;
mapping (uint32 => uint256) sops;
mapping (address => Account.State) a;
uint32 bip0Start;
uint32 hotFix3Start;
mapping (uint32 => Storage.Fundraiser) fundraisers;
uint32 fundraiserIndex;
mapping (address => bool) isBudget;
mapping(uint256 => bytes32) podListings;
mapping(bytes32 => uint256) podOrders;
mapping(address => Storage.AssetSilo) siloBalances;
mapping(address => Storage.SiloSettings) ss;
// These refund variables are intra-transaction state varables use to store refund amounts
uint256 refundStatus;
uint256 beanRefundAmount;
uint256 ethRefundAmount;
}
/*
SPDX-License-Identifier: MIT
*/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./libraries/Decimal.sol";
/**
* @author Publius
* @title C holds the contracts for Beanstalk.
**/
library C {
using Decimal for Decimal.D256;
using SafeMath for uint256;
// Constants
uint256 private constant PERCENT_BASE = 1e18; // Mainnet
// Chain
uint256 private constant CHAIN_ID = 1; // Mainnet
// Season
uint256 private constant CURRENT_SEASON_PERIOD = 3600; // 1 hour
// Sun
uint256 private constant HARVESET_PERCENTAGE = 0.5e18; // 50%
// Weather
uint256 private constant POD_RATE_LOWER_BOUND = 0.05e18; // 5%
uint256 private constant OPTIMAL_POD_RATE = 0.15e18; // 15%
uint256 private constant POD_RATE_UPPER_BOUND = 0.25e18; // 25%
uint256 private constant DELTA_POD_DEMAND_LOWER_BOUND = 0.95e18; // 95%
uint256 private constant DELTA_POD_DEMAND_UPPER_BOUND = 1.05e18; // 105%
uint32 private constant STEADY_SOW_TIME = 60; // 1 minute
uint256 private constant RAIN_TIME = 24; // 24 seasons = 1 day
// Governance
uint32 private constant GOVERNANCE_PERIOD = 168; // 168 seasons = 7 days
uint32 private constant GOVERNANCE_EMERGENCY_PERIOD = 86400; // 1 day
uint256 private constant GOVERNANCE_PASS_THRESHOLD = 5e17; // 1/2
uint256 private constant GOVERNANCE_EMERGENCY_THRESHOLD_NUMERATOR = 2; // 2/3
uint256 private constant GOVERNANCE_EMERGENCY_THRESHOLD_DEMONINATOR = 3; // 2/3
uint32 private constant GOVERNANCE_EXPIRATION = 24; // 24 seasons = 1 day
uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 0.001e18; // 0.1%
uint256 private constant BASE_COMMIT_INCENTIVE = 100e6; // 100 beans
uint256 private constant MAX_PROPOSITIONS = 5;
// Silo
uint256 private constant BASE_ADVANCE_INCENTIVE = 100e6; // 100 beans
uint32 private constant WITHDRAW_TIME = 25; // 24 + 1 seasons
uint256 private constant SEEDS_PER_BEAN = 2;
uint256 private constant SEEDS_PER_LP_BEAN = 4;
uint256 private constant STALK_PER_BEAN = 10000;
uint256 private constant ROOTS_BASE = 1e12;
// Field
uint256 private constant MAX_SOIL_DENOMINATOR = 4; // 25%
uint256 private constant COMPLEX_WEATHER_DENOMINATOR = 1000; // 0.1%
/**
* Getters
**/
function getSeasonPeriod() internal pure returns (uint256) {
return CURRENT_SEASON_PERIOD;
}
function getGovernancePeriod() internal pure returns (uint32) {
return GOVERNANCE_PERIOD;
}
function getGovernanceEmergencyPeriod() internal pure returns (uint32) {
return GOVERNANCE_EMERGENCY_PERIOD;
}
function getGovernanceExpiration() internal pure returns (uint32) {
return GOVERNANCE_EXPIRATION;
}
function getGovernancePassThreshold() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({value: GOVERNANCE_PASS_THRESHOLD});
}
function getGovernanceEmergencyThreshold() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(GOVERNANCE_EMERGENCY_THRESHOLD_NUMERATOR,GOVERNANCE_EMERGENCY_THRESHOLD_DEMONINATOR);
}
function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) {
return Decimal.D256({value: GOVERNANCE_PROPOSAL_THRESHOLD});
}
function getAdvanceIncentive() internal pure returns (uint256) {
return BASE_ADVANCE_INCENTIVE;
}
function getCommitIncentive() internal pure returns (uint256) {
return BASE_COMMIT_INCENTIVE;
}
function getSiloWithdrawSeasons() internal pure returns (uint32) {
return WITHDRAW_TIME;
}
function getComplexWeatherDenominator() internal pure returns (uint256) {
return COMPLEX_WEATHER_DENOMINATOR;
}
function getMaxSoilDenominator() internal pure returns (uint256) {
return MAX_SOIL_DENOMINATOR;
}
function getHarvestPercentage() internal pure returns (uint256) {
return HARVESET_PERCENTAGE;
}
function getChainId() internal pure returns (uint256) {
return CHAIN_ID;
}
function getOptimalPodRate() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(OPTIMAL_POD_RATE, PERCENT_BASE);
}
function getUpperBoundPodRate() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(POD_RATE_UPPER_BOUND, PERCENT_BASE);
}
function getLowerBoundPodRate() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(POD_RATE_LOWER_BOUND, PERCENT_BASE);
}
function getUpperBoundDPD() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(DELTA_POD_DEMAND_UPPER_BOUND, PERCENT_BASE);
}
function getLowerBoundDPD() internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(DELTA_POD_DEMAND_LOWER_BOUND, PERCENT_BASE);
}
function getSteadySowTime() internal pure returns (uint32) {
return STEADY_SOW_TIME;
}
function getRainTime() internal pure returns (uint256) {
return RAIN_TIME;
}
function getMaxPropositions() internal pure returns (uint256) {
return MAX_PROPOSITIONS;
}
function getSeedsPerBean() internal pure returns (uint256) {
return SEEDS_PER_BEAN;
}
function getSeedsPerLPBean() internal pure returns (uint256) {
return SEEDS_PER_LP_BEAN;
}
function getStalkPerBean() internal pure returns (uint256) {
return STALK_PER_BEAN;
}
function getStalkPerLPSeed() internal pure returns (uint256) {
return STALK_PER_BEAN/SEEDS_PER_LP_BEAN;
}
function getRootsBase() internal pure returns (uint256) {
return ROOTS_BASE;
}
}
/*
SPDX-License-Identifier: MIT
*/
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return one();
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
SPDX-License-Identifier: MIT
*/
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* EIP-2535 Diamonds: https://eips.ethereum.org/EIPS/eip-2535
/******************************************************************************/
import {IDiamondCut} from "../interfaces/IDiamondCut.sol";
import {IDiamondLoupe} from "../interfaces/IDiamondLoupe.sol";
import {IERC165} from "../interfaces/IERC165.sol";
import {IERC173} from "../interfaces/IERC173.sol";
import {LibMeta} from "./LibMeta.sol";
library LibDiamond {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct FacetAddressAndPosition {
address facetAddress;
uint96 functionSelectorPosition; // position in facetFunctionSelectors.functionSelectors array
}
struct FacetFunctionSelectors {
bytes4[] functionSelectors;
uint256 facetAddressPosition; // position of facetAddress in facetAddresses array
}
struct DiamondStorage {
// maps function selector to the facet address and
// the position of the selector in the facetFunctionSelectors.selectors array
mapping(bytes4 => FacetAddressAndPosition) selectorToFacetAndPosition;
// maps facet addresses to function selectors
mapping(address => FacetFunctionSelectors) facetFunctionSelectors;
// facet addresses
address[] facetAddresses;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// owner of the contract
address contractOwner;
}
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function setContractOwner(address _newOwner) internal {
DiamondStorage storage ds = diamondStorage();
address previousOwner = ds.contractOwner;
ds.contractOwner = _newOwner;
emit OwnershipTransferred(previousOwner, _newOwner);
}
function contractOwner() internal view returns (address contractOwner_) {
contractOwner_ = diamondStorage().contractOwner;
}
function enforceIsContractOwner() internal view {
require(msg.sender == diamondStorage().contractOwner, "LibDiamond: Must be contract owner");
}
event DiamondCut(IDiamondCut.FacetCut[] _diamondCut, address _init, bytes _calldata);
function addDiamondFunctions(
address _diamondCutFacet,
address _diamondLoupeFacet,
address _ownershipFacet
) internal {
IDiamondCut.FacetCut[] memory cut = new IDiamondCut.FacetCut[](3);
bytes4[] memory functionSelectors = new bytes4[](1);
functionSelectors[0] = IDiamondCut.diamondCut.selector;
cut[0] = IDiamondCut.FacetCut({facetAddress: _diamondCutFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
functionSelectors = new bytes4[](5);
functionSelectors[0] = IDiamondLoupe.facets.selector;
functionSelectors[1] = IDiamondLoupe.facetFunctionSelectors.selector;
functionSelectors[2] = IDiamondLoupe.facetAddresses.selector;
functionSelectors[3] = IDiamondLoupe.facetAddress.selector;
functionSelectors[4] = IERC165.supportsInterface.selector;
cut[1] = IDiamondCut.FacetCut({
facetAddress: _diamondLoupeFacet,
action: IDiamondCut.FacetCutAction.Add,
functionSelectors: functionSelectors
});
functionSelectors = new bytes4[](2);
functionSelectors[0] = IERC173.transferOwnership.selector;
functionSelectors[1] = IERC173.owner.selector;
cut[2] = IDiamondCut.FacetCut({facetAddress: _ownershipFacet, action: IDiamondCut.FacetCutAction.Add, functionSelectors: functionSelectors});
diamondCut(cut, address(0), "");
}
// Internal function version of diamondCut
function diamondCut(
IDiamondCut.FacetCut[] memory _diamondCut,
address _init,
bytes memory _calldata
) internal {
for (uint256 facetIndex; facetIndex < _diamondCut.length; facetIndex++) {
IDiamondCut.FacetCutAction action = _diamondCut[facetIndex].action;
if (action == IDiamondCut.FacetCutAction.Add) {
addFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Replace) {
replaceFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else if (action == IDiamondCut.FacetCutAction.Remove) {
removeFunctions(_diamondCut[facetIndex].facetAddress, _diamondCut[facetIndex].functionSelectors);
} else {
revert("LibDiamondCut: Incorrect FacetCutAction");
}
}
emit DiamondCut(_diamondCut, _init, _calldata);
initializeDiamondCut(_init, _calldata);
}
function addFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress == address(0), "LibDiamondCut: Can't add function that already exists");
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function replaceFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
require(_facetAddress != address(0), "LibDiamondCut: Add facet can't be address(0)");
uint96 selectorPosition = uint96(ds.facetFunctionSelectors[_facetAddress].functionSelectors.length);
// add new facet address if it does not exist
if (selectorPosition == 0) {
addFacet(ds, _facetAddress);
}
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
require(oldFacetAddress != _facetAddress, "LibDiamondCut: Can't replace function with same function");
removeFunction(ds, oldFacetAddress, selector);
addFunction(ds, selector, selectorPosition, _facetAddress);
selectorPosition++;
}
}
function removeFunctions(address _facetAddress, bytes4[] memory _functionSelectors) internal {
require(_functionSelectors.length > 0, "LibDiamondCut: No selectors in facet to cut");
DiamondStorage storage ds = diamondStorage();
// if function does not exist then do nothing and return
require(_facetAddress == address(0), "LibDiamondCut: Remove facet address must be address(0)");
for (uint256 selectorIndex; selectorIndex < _functionSelectors.length; selectorIndex++) {
bytes4 selector = _functionSelectors[selectorIndex];
address oldFacetAddress = ds.selectorToFacetAndPosition[selector].facetAddress;
removeFunction(ds, oldFacetAddress, selector);
}
}
function addFacet(DiamondStorage storage ds, address _facetAddress) internal {
enforceHasContractCode(_facetAddress, "LibDiamondCut: New facet has no code");
ds.facetFunctionSelectors[_facetAddress].facetAddressPosition = ds.facetAddresses.length;
ds.facetAddresses.push(_facetAddress);
}
function addFunction(DiamondStorage storage ds, bytes4 _selector, uint96 _selectorPosition, address _facetAddress) internal {
ds.selectorToFacetAndPosition[_selector].functionSelectorPosition = _selectorPosition;
ds.facetFunctionSelectors[_facetAddress].functionSelectors.push(_selector);
ds.selectorToFacetAndPosition[_selector].facetAddress = _facetAddress;
}
function removeFunction(DiamondStorage storage ds, address _facetAddress, bytes4 _selector) internal {
require(_facetAddress != address(0), "LibDiamondCut: Can't remove function that doesn't exist");
// an immutable function is a function defined directly in a diamond
require(_facetAddress != address(this), "LibDiamondCut: Can't remove immutable function");
// replace selector with last selector, then delete last selector
uint256 selectorPosition = ds.selectorToFacetAndPosition[_selector].functionSelectorPosition;
uint256 lastSelectorPosition = ds.facetFunctionSelectors[_facetAddress].functionSelectors.length - 1;
// if not the same then replace _selector with lastSelector
if (selectorPosition != lastSelectorPosition) {
bytes4 lastSelector = ds.facetFunctionSelectors[_facetAddress].functionSelectors[lastSelectorPosition];
ds.facetFunctionSelectors[_facetAddress].functionSelectors[selectorPosition] = lastSelector;
ds.selectorToFacetAndPosition[lastSelector].functionSelectorPosition = uint96(selectorPosition);
}
// delete the last selector
ds.facetFunctionSelectors[_facetAddress].functionSelectors.pop();
delete ds.selectorToFacetAndPosition[_selector];
// if no more selectors for facet address then delete the facet address
if (lastSelectorPosition == 0) {
// replace facet address with last facet address and delete last facet address
uint256 lastFacetAddressPosition = ds.facetAddresses.length - 1;
uint256 facetAddressPosition = ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
if (facetAddressPosition != lastFacetAddressPosition) {
address lastFacetAddress = ds.facetAddresses[lastFacetAddressPosition];
ds.facetAddresses[facetAddressPosition] = lastFacetAddress;
ds.facetFunctionSelectors[lastFacetAddress].facetAddressPosition = facetAddressPosition;
}
ds.facetAddresses.pop();
delete ds.facetFunctionSelectors[_facetAddress].facetAddressPosition;
}
}
function initializeDiamondCut(address _init, bytes memory _calldata) internal {
if (_init == address(0)) {
require(_calldata.length == 0, "LibDiamondCut: _init is address(0) but_calldata is not empty");
} else {
require(_calldata.length > 0, "LibDiamondCut: _calldata is empty but _init is not address(0)");
if (_init != address(this)) {
enforceHasContractCode(_init, "LibDiamondCut: _init address has no code");
}
(bool success, bytes memory error) = _init.delegatecall(_calldata);
if (!success) {
if (error.length > 0) {
// bubble up the error
revert(string(error));
} else {
revert("LibDiamondCut: _init function reverted");
}
}
}
}
function enforceHasContractCode(address _contract, string memory _errorMessage) internal view {
uint256 contractSize;
assembly {
contractSize := extcodesize(_contract)
}
require(contractSize > 0, _errorMessage);
}
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
/******************************************************************************\
* Author: Nick Mudge <[email protected]> (https://twitter.com/mudgen)
/******************************************************************************/
interface IDiamondCut {
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/// @notice Add/replace/remove any number of functions and optionally execute
/// a function with delegatecall
/// @param _diamondCut Contains the facet addresses and function selectors
/// @param _init The address of the contract or facet to execute _calldata
/// @param _calldata A function call, including function selector and arguments
/// _calldata is executed with delegatecall on _init
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface IDiamondLoupe {
/// These functions are expected to be called frequently
/// by tools.
struct Facet {
address facetAddress;
bytes4[] functionSelectors;
}
/// @notice Gets all facet addresses and their four byte function selectors.
/// @return facets_ Facet
function facets() external view returns (Facet[] memory facets_);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return facetFunctionSelectors_
function facetFunctionSelectors(address _facet) external view returns (bytes4[] memory facetFunctionSelectors_);
/// @notice Get all the facet addresses used by a diamond.
/// @return facetAddresses_
function facetAddresses() external view returns (address[] memory facetAddresses_);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return facetAddress_ The facet address.
function facetAddress(bytes4 _functionSelector) external view returns (address facetAddress_);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
/// @title ERC-173 Contract Ownership Standard
/// Note: the ERC-165 identifier for this interface is 0x7f5828d0
/* is ERC165 */
interface IERC173 {
/// @notice Get the address of the owner
/// @return owner_ The address of the owner.
function owner() external view returns (address owner_);
/// @notice Set the address of the new owner of the contract
/// @dev Set _newOwner to address(0) to renounce any ownership.
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
/*
SPDX-License-Identifier: MIT
*/
pragma experimental ABIEncoderV2;
pragma solidity =0.7.6;
library LibMeta {
bytes32 internal constant EIP712_DOMAIN_TYPEHASH =
keccak256(bytes("EIP712Domain(string name,string version,uint256 salt,address verifyingContract)"));
function domainSeparator(string memory name, string memory version) internal view returns (bytes32 domainSeparator_) {
domainSeparator_ = keccak256(
abi.encode(EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(version)), getChainID(), address(this))
);
}
function getChainID() internal pure returns (uint256 id) {
assembly {
id := chainid()
}
}
function msgSender() internal view returns (address sender_) {
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender_ := and(mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
} else {
sender_ = msg.sender;
}
}
}
// 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);
} | @notice log_two calculates the log2 solution in a gas efficient manner Motivation: https://ethereum.stackexchange.com/questions/8086 @param x - the base to calculate log2 of | function log_two(uint x) private pure returns (uint y) {
assembly {
let arg := x
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)))
}
}
| 1,316,875 | [
1,
1330,
67,
15415,
17264,
326,
613,
22,
6959,
316,
279,
16189,
14382,
21296,
490,
352,
8482,
30,
2333,
2207,
546,
822,
379,
18,
3772,
16641,
18,
832,
19,
9758,
19,
3672,
5292,
225,
619,
300,
326,
1026,
358,
4604,
613,
22,
434,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
613,
67,
15415,
12,
11890,
619,
13,
3238,
16618,
1135,
261,
11890,
677,
13,
288,
203,
3639,
19931,
288,
203,
5411,
2231,
1501,
519,
619,
203,
5411,
619,
519,
720,
12,
92,
16,
21,
13,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
3103,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
3028,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
2163,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
6625,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
23899,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
21,
12648,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
21,
12648,
12648,
3719,
203,
5411,
619,
519,
578,
12,
92,
16,
3739,
12,
92,
16,
374,
92,
21,
12648,
12648,
12648,
12648,
3719,
203,
5411,
619,
519,
527,
12,
92,
16,
404,
13,
203,
5411,
2231,
312,
519,
312,
945,
12,
20,
92,
7132,
13,
203,
5411,
312,
2233,
12,
81,
16,
374,
5841,
28,
74,
29,
7358,
507,
73,
26,
952,
8285,
74,
2196,
3030,
27,
4315,
71,
23,
69,
4033,
11180,
2180,
8522,
24,
74,
20,
73,
28,
9897,
72,
28,
27832,
24,
7301,
70,
26,
69,
6030,
69,
27,
69,
25,
69,
23,
73,
21,
73,
8313,
13,
203,
5411,
312,
2233,
2
] |
pragma solidity ^0.4.23;
import "./BaseContentManagement.sol";
contract Catalog{
struct Content {
bytes32 name;
uint64 views;
}
uint public premiumCost = 0.1 ether;
uint public premiumTime = 10000 /*Block height*/;
address private owner;
uint64 totalViews = 0;
bytes32[] internal contentsName;
mapping(bytes32 => uint) public name2cost;
mapping(bytes32 => address) public name2address;
mapping (address => uint) internal premiumEndBlockNumber;
//mapping (string => Content) internal author2mostPopular;
//mapping(uint => bytes32) internal genre2mostPopular;
//mapping(uint => uint64) internal genre2mostPopularCounter;
event ContentConsumed(bytes32 _content, address _user);
event ContentBought(bytes32 _content, address _user);
event GiftContentBought(address _from, address _to, bytes32 _content);
event GiftPremiumSubscription(address _from, address _to);
event PublishedContent(address _content, bytes32 _contentName);
event PremiumSubscriptionBought(address _user);
event PaymentTriggered();
constructor () public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/* Check if the user has a valid premium subscription */
function isPremium(address _user) view external returns (bool) {
return premiumEndBlockNumber[_user] > block.number;
}
/* simple wrapper for content */
function isGranted(address _user, address _content) view external returns (bool) {
BaseContentManagement cont = BaseContentManagement(_content);
return cont.hasAccess(_user);
}
function getStatistics() external view returns (bytes32[], uint[]){
uint[] memory views = new uint[](contentsName.length);
for(uint i = 0; i<contentsName.length; i++){
BaseContentManagement cont = BaseContentManagement(name2address[contentsName[i]]);
views[i] = cont.views();
}
return (contentsName, views);
}
function getContentList() view external returns (bytes32[]){
return contentsName;
}
function getNewContentList(uint _n) external view returns (bytes32[]){
int startIndex = int(contentsName.length) - int(_n);
if(startIndex > 0){
bytes32[] memory result = new bytes32[](_n);
uint j = 0;
for(uint i = uint(startIndex); i<contentsName.length; i++){
result[j] = contentsName[i];
j++;
}
return result;
}
return contentsName;
}
function getLatestByGenre(uint _g) external view returns (bytes32){
uint i = contentsName.length - 1;
while(i >= 0){
BaseContentManagement c = BaseContentManagement(name2address[contentsName[i]]);
BaseContentManagement.Genre _gc = c.genre();
if(BaseContentManagement.Genre(_g) == _gc){
return contentsName[i];
}
i--;
}
return 0x0;
}
function getMostPopularByGenre(uint _g) external view returns (bytes32){
//return genre2mostPopular[_g];
bytes32 name;
uint count = 0;
for(uint i = 0; i<contentsName.length; i++){
BaseContentManagement c = BaseContentManagement(name2address[contentsName[i]]);
if( uint(c.genre()) == _g && count < c.views() ){
name = c.name();
}
}
return name;
}
function getLatestByAuthor(string author) external view returns (bytes32){
uint i = contentsName.length - 1;
while(i >= 0){
BaseContentManagement c = BaseContentManagement(name2address[contentsName[i]]);
if(keccak256(abi.encodePacked(author)) == keccak256(abi.encodePacked(c.author())) ){
return contentsName[i];
}
i--;
}
}
function getMostPopularByAuthor(string author) external view returns (bytes32){
//return author2mostPopular[author].name;
bytes32 name;
uint count = 0;
for(uint i = 0; i<contentsName.length; i++){
BaseContentManagement c = BaseContentManagement(name2address[contentsName[i]]);
if( keccak256(abi.encodePacked(author)) == keccak256(abi.encodePacked(c.author())) && c.views() > count ){
name = c.name();
}
}
return name;
}
function consumeContent(bytes32 _contentName, uint viewsFromPayment) external {
require(msg.sender == name2address[_contentName], "This function is callable only from the content");
totalViews++;
if(viewsFromPayment == 100){
BaseContentManagement content = BaseContentManagement(name2address[_contentName]);
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = content.ratingMean();
content.resetViewsAndGetMoney.value(content.contentCost() * uint(content.viewsFromLastPayment()) * (_fair+_cool+_appr)/(3*254))();
}
emit ContentConsumed(_contentName, tx.origin);
emit PaymentTriggered();
}
function publishContent(address _addr) external{
BaseContentManagement c = BaseContentManagement(_addr);
assert(c.setCatalogAddress(address(this)));
assert(c.views() == 0);
assert(c.viewsFromLastPayment() == 0);
contentsName.push(c.name());
name2address[c.name()] = _addr;
name2cost[c.name()] = c.contentCost();
emit PublishedContent(_addr, c.name());
}
/* Set, for the sender, the right to access to the content */
function grantAccess(bytes32 _content) external payable {
require(msg.value == name2cost[_content], "You have to pay some ether for this content");
BaseContentManagement b = BaseContentManagement(name2address[_content]);
b.grantAccess(msg.sender);
emit ContentBought(_content, msg.sender);
}
function giftContent(bytes32 _contentName, address _userAddr) external payable {
require(msg.value == name2cost[_contentName]);
BaseContentManagement b = BaseContentManagement(name2address[_contentName]);
b.grantAccess(_userAddr);
emit GiftContentBought(msg.sender, _userAddr, _contentName);
}
function giftPremium(address _user) external payable{
require(msg.value == premiumCost);
/* The following condition check if there is some active subscription, if it is
the subscription is an extention of the existing one */
if(premiumEndBlockNumber[_user] > block.number){
premiumEndBlockNumber[_user] = premiumEndBlockNumber[_user] + premiumTime;
} else {
premiumEndBlockNumber[_user] = block.number + premiumTime;
}
emit GiftPremiumSubscription(msg.sender, _user);
}
function buyPremium() external payable{
require(msg.value == premiumCost);
/* The following condition check if there is some active subscription, if it is
the subscription is an extention of the existing one */
if(premiumEndBlockNumber[msg.sender] > block.number){
premiumEndBlockNumber[msg.sender] = premiumEndBlockNumber[msg.sender] + premiumTime;
} else {
premiumEndBlockNumber[msg.sender] = block.number + premiumTime;
}
emit PremiumSubscriptionBought(msg.sender);
}
function goodbye() external onlyOwner(){
/* pay the content not already paid */
for(uint i = 0; i<contentsName.length; i++){
BaseContentManagement content = BaseContentManagement(name2address[contentsName[i]]);
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = content.ratingMean();
content.resetViewsAndGetMoney.value(content.contentCost() * uint(content.viewsFromLastPayment()) * (_fair+_cool+_appr)/(3*254))();
}
/* Divide the subscription premium cost amoung all the contents w.r.t. their total views */
for(i = 0; i<contentsName.length; i++){
content = BaseContentManagement(name2address[contentsName[i]]);
address(name2address[contentsName[i]]).transfer(address(this).balance/totalViews * uint(content.views()));
}
selfdestruct(owner); /* The remaining money, are sent to owner */
}
function bytes32ToString(bytes32 x) pure public 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);
}
function GetMostRated(uint _category) external view returns (bytes32){
BaseContentManagement cont0 = BaseContentManagement(name2address[contentsName[0]]);
bytes32 top = contentsName[0];
BaseContentManagement.Rating memory toprate;
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = cont0.ratingMean();
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
for(uint i = 1; i<contentsName.length; i++){
BaseContentManagement cont = BaseContentManagement(name2address[contentsName[i]]);
(_fair, _cool, _appr) = cont.ratingMean();
if(_category == 0){
if(_fair > toprate.fairness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 1){
if(_cool > toprate.coolness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 2){
if(_appr > toprate.appreciation){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
}
}
return top;
}
function GetMostRatedByGenre(uint _genre, uint _category) view external returns (bytes32){
BaseContentManagement cont0 = BaseContentManagement(name2address[contentsName[0]]);
bytes32 top = contentsName[0];
BaseContentManagement.Rating memory toprate;
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = cont0.ratingMean();
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
for(uint i = 1; i<contentsName.length; i++){
BaseContentManagement cont = BaseContentManagement(name2address[contentsName[i]]);
if(cont.genre() == BaseContentManagement.Genre(_genre)){
(_fair, _cool, _appr) = cont.ratingMean();
if(_category == 0){
if(_fair > toprate.fairness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 1){
if(_cool > toprate.coolness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 2){
if(_appr > toprate.appreciation){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
}
}
}
}
function GetMostRatedByAuthor(string _author, uint _category) view external returns (bytes32){
BaseContentManagement cont0 = BaseContentManagement(name2address[contentsName[0]]);
bytes32 top = contentsName[0];
BaseContentManagement.Rating memory toprate;
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = cont0.ratingMean();
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
for(uint i = 1; i<contentsName.length; i++){
BaseContentManagement cont = BaseContentManagement(name2address[contentsName[i]]);
if( keccak256(abi.encodePacked(cont.author())) == keccak256(abi.encodePacked(_author))){
(_fair, _cool, _appr) = cont.ratingMean();
if(_category == 0){
if(_fair > toprate.fairness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 1){
if(_cool > toprate.coolness){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
} else if(_category == 2){
if(_appr > toprate.appreciation){
toprate = BaseContentManagement.Rating(_fair, _cool, _appr);
top = contentsName[i];
}
}
}
}
}
} | pay the content not already paid */ Divide the subscription premium cost amoung all the contents w.r.t. their total views */ | function goodbye() external onlyOwner(){
for(uint i = 0; i<contentsName.length; i++){
BaseContentManagement content = BaseContentManagement(name2address[contentsName[i]]);
uint8 _fair;
uint8 _cool;
uint8 _appr;
(_fair, _cool, _appr) = content.ratingMean();
content.resetViewsAndGetMoney.value(content.contentCost() * uint(content.viewsFromLastPayment()) * (_fair+_cool+_appr)/(3*254))();
}
for(i = 0; i<contentsName.length; i++){
content = BaseContentManagement(name2address[contentsName[i]]);
address(name2address[contentsName[i]]).transfer(address(this).balance/totalViews * uint(content.views()));
}
selfdestruct(owner); /* The remaining money, are sent to owner */
}
| 12,894,477 | [
1,
10239,
326,
913,
486,
1818,
30591,
342,
21411,
831,
326,
4915,
23020,
5077,
6991,
2125,
465,
75,
777,
326,
2939,
341,
18,
86,
18,
88,
18,
3675,
2078,
7361,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
7494,
1637,
73,
1435,
3903,
1338,
5541,
1435,
95,
203,
3639,
364,
12,
11890,
277,
273,
374,
31,
277,
32,
3980,
461,
18,
2469,
31,
277,
27245,
95,
203,
5411,
3360,
1350,
10998,
913,
273,
3360,
1350,
10998,
12,
529,
22,
2867,
63,
3980,
461,
63,
77,
13563,
1769,
203,
5411,
2254,
28,
389,
507,
481,
31,
7010,
5411,
2254,
28,
389,
71,
1371,
31,
7010,
5411,
2254,
28,
389,
438,
683,
31,
203,
5411,
261,
67,
507,
481,
16,
389,
71,
1371,
16,
389,
438,
683,
13,
273,
913,
18,
17326,
15312,
5621,
203,
5411,
913,
18,
6208,
9959,
14042,
23091,
18,
1132,
12,
1745,
18,
1745,
8018,
1435,
380,
2254,
12,
1745,
18,
7061,
1265,
3024,
6032,
10756,
380,
261,
67,
507,
481,
15,
67,
71,
1371,
15,
67,
438,
683,
13176,
12,
23,
14,
26261,
3719,
5621,
203,
3639,
289,
203,
3639,
364,
12,
77,
273,
374,
31,
277,
32,
3980,
461,
18,
2469,
31,
277,
27245,
95,
203,
5411,
913,
273,
3360,
1350,
10998,
12,
529,
22,
2867,
63,
3980,
461,
63,
77,
13563,
1769,
203,
5411,
1758,
12,
529,
22,
2867,
63,
3980,
461,
63,
77,
13563,
2934,
13866,
12,
2867,
12,
2211,
2934,
12296,
19,
4963,
9959,
380,
2254,
12,
1745,
18,
7061,
1435,
10019,
203,
3639,
289,
203,
3639,
365,
5489,
8813,
12,
8443,
1769,
1748,
1021,
4463,
15601,
16,
854,
3271,
358,
3410,
1195,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-29
*/
// Sources flattened with hardhat v2.6.4 https://hardhat.org
// File contracts/lib/RLPReader.sol
/*
* @author Hamdi Allam [email protected]
* Please reach out with any questions or concerns
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library RLPReader {
uint8 constant STRING_SHORT_START = 0x80;
uint8 constant STRING_LONG_START = 0xb8;
uint8 constant LIST_SHORT_START = 0xc0;
uint8 constant LIST_LONG_START = 0xf8;
uint8 constant WORD_SIZE = 32;
struct RLPItem {
uint len;
uint memPtr;
}
struct Iterator {
RLPItem item; // Item that's being iterated over.
uint nextPtr; // Position of the next item in the list.
}
/*
* @dev Returns the next element in the iteration. Reverts if it has not next element.
* @param self The iterator.
* @return The next element in the iteration.
*/
function next(Iterator memory self) internal pure returns (RLPItem memory) {
require(hasNext(self));
uint ptr = self.nextPtr;
uint itemLength = _itemLength(ptr);
self.nextPtr = ptr + itemLength;
return RLPItem(itemLength, ptr);
}
/*
* @dev Returns true if the iteration has more elements.
* @param self The iterator.
* @return true if the iteration has more elements.
*/
function hasNext(Iterator memory self) internal pure returns (bool) {
RLPItem memory item = self.item;
return self.nextPtr < item.memPtr + item.len;
}
/*
* @param item RLP encoded bytes
*/
function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) {
uint memPtr;
assembly {
memPtr := add(item, 0x20)
}
return RLPItem(item.length, memPtr);
}
/*
* @dev Create an iterator. Reverts if item is not a list.
* @param self The RLP item.
* @return An 'Iterator' over the item.
*/
function iterator(RLPItem memory self) internal pure returns (Iterator memory) {
require(isList(self));
uint ptr = self.memPtr + _payloadOffset(self.memPtr);
return Iterator(self, ptr);
}
/*
* @param item RLP encoded bytes
*/
function rlpLen(RLPItem memory item) internal pure returns (uint) {
return item.len;
}
/*
* @param item RLP encoded bytes
*/
function payloadLen(RLPItem memory item) internal pure returns (uint) {
return item.len - _payloadOffset(item.memPtr);
}
/*
* @param item RLP encoded list in bytes
*/
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) {
require(isList(item));
uint items = numItems(item);
RLPItem[] memory result = new RLPItem[](items);
uint memPtr = item.memPtr + _payloadOffset(item.memPtr);
uint dataLen;
for (uint i = 0; i < items; i++) {
dataLen = _itemLength(memPtr);
result[i] = RLPItem(dataLen, memPtr);
memPtr = memPtr + dataLen;
}
return result;
}
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) {
if (item.len == 0) return false;
uint8 byte0;
uint memPtr = item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START)
return false;
return true;
}
/*
* @dev A cheaper version of keccak256(toRlpBytes(item)) that avoids copying memory.
* @return keccak256 hash of RLP encoded bytes.
*/
function rlpBytesKeccak256(RLPItem memory item) internal pure returns (bytes32) {
uint256 ptr = item.memPtr;
uint256 len = item.len;
bytes32 result;
assembly {
result := keccak256(ptr, len)
}
return result;
}
function payloadLocation(RLPItem memory item) internal pure returns (uint, uint) {
uint offset = _payloadOffset(item.memPtr);
uint memPtr = item.memPtr + offset;
uint len = item.len - offset; // data length
return (memPtr, len);
}
/*
* @dev A cheaper version of keccak256(toBytes(item)) that avoids copying memory.
* @return keccak256 hash of the item payload.
*/
function payloadKeccak256(RLPItem memory item) internal pure returns (bytes32) {
(uint memPtr, uint len) = payloadLocation(item);
bytes32 result;
assembly {
result := keccak256(memPtr, len)
}
return result;
}
/** RLPItem conversions into data types **/
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) {
bytes memory result = new bytes(item.len);
if (result.length == 0) return result;
uint ptr;
assembly {
ptr := add(0x20, result)
}
copy(item.memPtr, ptr, item.len);
return result;
}
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) {
require(item.len == 1);
uint result;
uint memPtr = item.memPtr;
assembly {
result := byte(0, mload(memPtr))
}
return result == 0 ? false : true;
}
function toAddress(RLPItem memory item) internal pure returns (address) {
// 1 byte for the length prefix
require(item.len == 21);
return address(uint160(toUint(item)));
}
function toUint(RLPItem memory item) internal pure returns (uint) {
require(item.len > 0 && item.len <= 33);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset;
uint result;
uint memPtr = item.memPtr + offset;
assembly {
result := mload(memPtr)
// shfit to the correct location if neccesary
if lt(len, 32) {
result := div(result, exp(256, sub(32, len)))
}
}
return result;
}
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) {
// one byte prefix
require(item.len == 33);
uint result;
uint memPtr = item.memPtr + 1;
assembly {
result := mload(memPtr)
}
return result;
}
function toBytes(RLPItem memory item) internal pure returns (bytes memory) {
require(item.len > 0);
uint offset = _payloadOffset(item.memPtr);
uint len = item.len - offset; // data length
bytes memory result = new bytes(len);
uint destPtr;
assembly {
destPtr := add(0x20, result)
}
copy(item.memPtr + offset, destPtr, len);
return result;
}
/*
* Private Helpers
*/
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) {
if (item.len == 0) return 0;
uint count = 0;
uint currPtr = item.memPtr + _payloadOffset(item.memPtr);
uint endPtr = item.memPtr + item.len;
while (currPtr < endPtr) {
currPtr = currPtr + _itemLength(currPtr); // skip over an item
count++;
}
return count;
}
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) {
uint itemLen;
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
itemLen = 1;
else if (byte0 < STRING_LONG_START)
itemLen = byte0 - STRING_SHORT_START + 1;
else if (byte0 < LIST_SHORT_START) {
assembly {
let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is
memPtr := add(memPtr, 1) // skip over the first byte
/* 32 byte word size */
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len
itemLen := add(dataLen, add(byteLen, 1))
}
}
else if (byte0 < LIST_LONG_START) {
itemLen = byte0 - LIST_SHORT_START + 1;
}
else {
assembly {
let byteLen := sub(byte0, 0xf7)
memPtr := add(memPtr, 1)
let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length
itemLen := add(dataLen, add(byteLen, 1))
}
}
return itemLen;
}
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) {
uint byte0;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < STRING_SHORT_START)
return 0;
else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START))
return 1;
else if (byte0 < LIST_SHORT_START) // being explicit
return byte0 - (STRING_LONG_START - 1) + 1;
else
return byte0 - (LIST_LONG_START - 1) + 1;
}
/*
* @param src Pointer to source
* @param dest Pointer to destination
* @param len Amount of memory to copy from the source
*/
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
if (len == 0) return;
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
}
// File contracts/lib/MerklePatriciaProof.sol
library MerklePatriciaProof {
/*
* @dev Verifies a merkle patricia proof.
* @param value The terminating value in the trie.
* @param encodedPath The path in the trie leading to value.
* @param rlpParentNodes The rlp encoded stack of nodes.
* @param root The root hash of the trie.
* @return The boolean validity of the proof.
*/
function verify(
bytes memory value,
bytes memory encodedPath,
bytes memory rlpParentNodes,
bytes32 root
) internal pure returns (bool) {
RLPReader.RLPItem memory item = RLPReader.toRlpItem(rlpParentNodes);
RLPReader.RLPItem[] memory parentNodes = RLPReader.toList(item);
bytes memory currentNode;
RLPReader.RLPItem[] memory currentNodeList;
bytes32 nodeKey = root;
uint256 pathPtr = 0;
bytes memory path = _getNibbleArray(encodedPath);
if (path.length == 0) {
return false;
}
for (uint256 i = 0; i < parentNodes.length; i++) {
if (pathPtr > path.length) {
return false;
}
currentNode = RLPReader.toRlpBytes(parentNodes[i]);
if (nodeKey != keccak256(currentNode)) {
return false;
}
currentNodeList = RLPReader.toList(parentNodes[i]);
if (currentNodeList.length == 17) {
if (pathPtr == path.length) {
if (
keccak256(RLPReader.toBytes(currentNodeList[16])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
uint8 nextPathNibble = uint8(path[pathPtr]);
if (nextPathNibble > 16) {
return false;
}
nodeKey = bytes32(
RLPReader.toUintStrict(currentNodeList[nextPathNibble])
);
pathPtr += 1;
} else if (currentNodeList.length == 2) {
uint256 traversed = _nibblesToTraverse(
RLPReader.toBytes(currentNodeList[0]),
path,
pathPtr
);
if (pathPtr + traversed == path.length) {
//leaf node
if (
keccak256(RLPReader.toBytes(currentNodeList[1])) ==
keccak256(value)
) {
return true;
} else {
return false;
}
}
//extension node
if (traversed == 0) {
return false;
}
pathPtr += traversed;
nodeKey = bytes32(RLPReader.toUintStrict(currentNodeList[1]));
} else {
return false;
}
}
}
function _nibblesToTraverse(
bytes memory encodedPartialPath,
bytes memory path,
uint256 pathPtr
) private pure returns (uint256) {
uint256 len = 0;
// encodedPartialPath has elements that are each two hex characters (1 byte), but partialPath
// and slicedPath have elements that are each one hex character (1 nibble)
bytes memory partialPath = _getNibbleArray(encodedPartialPath);
bytes memory slicedPath = new bytes(partialPath.length);
// pathPtr counts nibbles in path
// partialPath.length is a number of nibbles
for (uint256 i = pathPtr; i < pathPtr + partialPath.length; i++) {
bytes1 pathNibble = path[i];
slicedPath[i - pathPtr] = pathNibble;
}
if (keccak256(partialPath) == keccak256(slicedPath)) {
len = partialPath.length;
} else {
len = 0;
}
return len;
}
// bytes b must be hp encoded
function _getNibbleArray(bytes memory b)
internal
pure
returns (bytes memory)
{
bytes memory nibbles = "";
if (b.length > 0) {
uint8 offset;
uint8 hpNibble = uint8(_getNthNibbleOfBytes(0, b));
if (hpNibble == 1 || hpNibble == 3) {
nibbles = new bytes(b.length * 2 - 1);
bytes1 oddNibble = _getNthNibbleOfBytes(1, b);
nibbles[0] = oddNibble;
offset = 1;
} else {
nibbles = new bytes(b.length * 2 - 2);
offset = 0;
}
for (uint256 i = offset; i < nibbles.length; i++) {
nibbles[i] = _getNthNibbleOfBytes(i - offset + 2, b);
}
}
return nibbles;
}
function _getNthNibbleOfBytes(uint256 n, bytes memory str)
private
pure
returns (bytes1)
{
return
bytes1(
n % 2 == 0 ? uint8(str[n / 2]) / 0x10 : uint8(str[n / 2]) % 0x10
);
}
}
// File contracts/lib/Merkle.sol
library Merkle {
function checkMembership(
bytes32 leaf,
uint256 index,
bytes32 rootHash,
bytes memory proof
) internal pure returns (bool) {
require(proof.length % 32 == 0, "Invalid proof length");
uint256 proofHeight = proof.length / 32;
// Proof of size n means, height of the tree is n+1.
// In a tree of height n+1, max #leafs possible is 2 ^ n
require(index < 2 ** proofHeight, "Leaf index is too big");
bytes32 proofElement;
bytes32 computedHash = leaf;
for (uint256 i = 32; i <= proof.length; i += 32) {
assembly {
proofElement := mload(add(proof, i))
}
if (index % 2 == 0) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
index = index / 2;
}
return computedHash == rootHash;
}
}
// File contracts/lib/ExitPayloadReader.sol
library ExitPayloadReader {
using RLPReader for bytes;
using RLPReader for RLPReader.RLPItem;
uint8 constant WORD_SIZE = 32;
struct ExitPayload {
RLPReader.RLPItem[] data;
}
struct Receipt {
RLPReader.RLPItem[] data;
bytes raw;
uint256 logIndex;
}
struct Log {
RLPReader.RLPItem data;
RLPReader.RLPItem[] list;
}
struct LogTopics {
RLPReader.RLPItem[] data;
}
// copy paste of private copy() from RLPReader to avoid changing of existing contracts
function copy(uint src, uint dest, uint len) private pure {
if (len == 0) return;
// copy as many word sizes as possible
for (; len >= WORD_SIZE; len -= WORD_SIZE) {
assembly {
mstore(dest, mload(src))
}
src += WORD_SIZE;
dest += WORD_SIZE;
}
// left over bytes. Mask is used to remove unwanted bytes from the word
uint mask = 256 ** (WORD_SIZE - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask)) // zero out src
let destpart := and(mload(dest), mask) // retrieve the bytes
mstore(dest, or(destpart, srcpart))
}
}
function toExitPayload(bytes memory data)
internal
pure
returns (ExitPayload memory)
{
RLPReader.RLPItem[] memory payloadData = data
.toRlpItem()
.toList();
return ExitPayload(payloadData);
}
function getHeaderNumber(ExitPayload memory payload) internal pure returns(uint256) {
return payload.data[0].toUint();
}
function getBlockProof(ExitPayload memory payload) internal pure returns(bytes memory) {
return payload.data[1].toBytes();
}
function getBlockNumber(ExitPayload memory payload) internal pure returns(uint256) {
return payload.data[2].toUint();
}
function getBlockTime(ExitPayload memory payload) internal pure returns(uint256) {
return payload.data[3].toUint();
}
function getTxRoot(ExitPayload memory payload) internal pure returns(bytes32) {
return bytes32(payload.data[4].toUint());
}
function getReceiptRoot(ExitPayload memory payload) internal pure returns(bytes32) {
return bytes32(payload.data[5].toUint());
}
function getReceipt(ExitPayload memory payload) internal pure returns(Receipt memory receipt) {
receipt.raw = payload.data[6].toBytes();
RLPReader.RLPItem memory receiptItem = receipt.raw.toRlpItem();
if (receiptItem.isList()) {
// legacy tx
receipt.data = receiptItem.toList();
} else {
// pop first byte before parsting receipt
bytes memory typedBytes = receipt.raw;
bytes memory result = new bytes(typedBytes.length - 1);
uint256 srcPtr;
uint256 destPtr;
assembly {
srcPtr := add(33, typedBytes)
destPtr := add(0x20, result)
}
copy(srcPtr, destPtr, result.length);
receipt.data = result.toRlpItem().toList();
}
receipt.logIndex = getReceiptLogIndex(payload);
return receipt;
}
function getReceiptProof(ExitPayload memory payload) internal pure returns(bytes memory) {
return payload.data[7].toBytes();
}
function getBranchMaskAsBytes(ExitPayload memory payload) internal pure returns(bytes memory) {
return payload.data[8].toBytes();
}
function getBranchMaskAsUint(ExitPayload memory payload) internal pure returns(uint256) {
return payload.data[8].toUint();
}
function getReceiptLogIndex(ExitPayload memory payload) internal pure returns(uint256) {
return payload.data[9].toUint();
}
// Receipt methods
function toBytes(Receipt memory receipt) internal pure returns(bytes memory) {
return receipt.raw;
}
function getLog(Receipt memory receipt) internal pure returns(Log memory) {
RLPReader.RLPItem memory logData = receipt.data[3].toList()[receipt.logIndex];
return Log(logData, logData.toList());
}
// Log methods
function getEmitter(Log memory log) internal pure returns(address) {
return RLPReader.toAddress(log.list[0]);
}
function getTopics(Log memory log) internal pure returns(LogTopics memory) {
return LogTopics(log.list[1].toList());
}
function getData(Log memory log) internal pure returns(bytes memory) {
return log.list[2].toBytes();
}
function toRlpBytes(Log memory log) internal pure returns(bytes memory) {
return log.data.toRlpBytes();
}
// LogTopics methods
function getField(LogTopics memory topics, uint256 index) internal pure returns(RLPReader.RLPItem memory) {
return topics.data[index];
}
}
// File contracts/tunnel/FxBaseRootTunnel.sol
interface IFxStateSender {
function sendMessageToChild(address _receiver, bytes calldata _data) external;
}
contract ICheckpointManager {
struct HeaderBlock {
bytes32 root;
uint256 start;
uint256 end;
uint256 createdAt;
address proposer;
}
/**
* @notice mapping of checkpoint header numbers to block details
* @dev These checkpoints are submited by plasma contracts
*/
mapping(uint256 => HeaderBlock) public headerBlocks;
}
abstract contract FxBaseRootTunnel {
using RLPReader for RLPReader.RLPItem;
using Merkle for bytes32;
using ExitPayloadReader for bytes;
using ExitPayloadReader for ExitPayloadReader.ExitPayload;
using ExitPayloadReader for ExitPayloadReader.Log;
using ExitPayloadReader for ExitPayloadReader.LogTopics;
using ExitPayloadReader for ExitPayloadReader.Receipt;
// keccak256(MessageSent(bytes))
bytes32 public constant SEND_MESSAGE_EVENT_SIG = 0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036;
// state sender contract
IFxStateSender public fxRoot;
// root chain manager
ICheckpointManager public checkpointManager;
// child tunnel contract which receives and sends messages
address public fxChildTunnel;
// storage to avoid duplicate exits
mapping(bytes32 => bool) public processedExits;
constructor(address _checkpointManager, address _fxRoot) {
checkpointManager = ICheckpointManager(_checkpointManager);
fxRoot = IFxStateSender(_fxRoot);
}
// set fxChildTunnel if not set already
function setFxChildTunnel(address _fxChildTunnel) public {
require(fxChildTunnel == address(0x0), "FxBaseRootTunnel: CHILD_TUNNEL_ALREADY_SET");
fxChildTunnel = _fxChildTunnel;
}
/**
* @notice Send bytes message to Child Tunnel
* @param message bytes message that will be sent to Child Tunnel
* some message examples -
* abi.encode(tokenId);
* abi.encode(tokenId, tokenMetadata);
* abi.encode(messageType, messageData);
*/
function _sendMessageToChild(bytes memory message) internal {
fxRoot.sendMessageToChild(fxChildTunnel, message);
}
function _validateAndExtractMessage(bytes memory inputData) internal returns (bytes memory) {
ExitPayloadReader.ExitPayload memory payload = inputData.toExitPayload();
bytes memory branchMaskBytes = payload.getBranchMaskAsBytes();
uint256 blockNumber = payload.getBlockNumber();
// checking if exit has already been processed
// unique exit is identified using hash of (blockNumber, branchMask, receiptLogIndex)
bytes32 exitHash = keccak256(
abi.encodePacked(
blockNumber,
// first 2 nibbles are dropped while generating nibble array
// this allows branch masks that are valid but bypass exitHash check (changing first 2 nibbles only)
// so converting to nibble array and then hashing it
MerklePatriciaProof._getNibbleArray(branchMaskBytes),
payload.getReceiptLogIndex()
)
);
require(
processedExits[exitHash] == false,
"FxRootTunnel: EXIT_ALREADY_PROCESSED"
);
processedExits[exitHash] = true;
ExitPayloadReader.Receipt memory receipt = payload.getReceipt();
ExitPayloadReader.Log memory log = receipt.getLog();
// check child tunnel
require(fxChildTunnel == log.getEmitter(), "FxRootTunnel: INVALID_FX_CHILD_TUNNEL");
bytes32 receiptRoot = payload.getReceiptRoot();
// verify receipt inclusion
require(
MerklePatriciaProof.verify(
receipt.toBytes(),
branchMaskBytes,
payload.getReceiptProof(),
receiptRoot
),
"FxRootTunnel: INVALID_RECEIPT_PROOF"
);
// verify checkpoint inclusion
_checkBlockMembershipInCheckpoint(
blockNumber,
payload.getBlockTime(),
payload.getTxRoot(),
receiptRoot,
payload.getHeaderNumber(),
payload.getBlockProof()
);
ExitPayloadReader.LogTopics memory topics = log.getTopics();
require(
bytes32(topics.getField(0).toUint()) == SEND_MESSAGE_EVENT_SIG, // topic0 is event sig
"FxRootTunnel: INVALID_SIGNATURE"
);
// received message data
(bytes memory message) = abi.decode(log.getData(), (bytes)); // event decodes params again, so decoding bytes to get message
return message;
}
function _checkBlockMembershipInCheckpoint(
uint256 blockNumber,
uint256 blockTime,
bytes32 txRoot,
bytes32 receiptRoot,
uint256 headerNumber,
bytes memory blockProof
) private view returns (uint256) {
(
bytes32 headerRoot,
uint256 startBlock,
,
uint256 createdAt,
) = checkpointManager.headerBlocks(headerNumber);
require(
keccak256(
abi.encodePacked(blockNumber, blockTime, txRoot, receiptRoot)
)
.checkMembership(
blockNumber-startBlock,
headerRoot,
blockProof
),
"FxRootTunnel: INVALID_HEADER"
);
return createdAt;
}
/**
* @notice receive message from L2 to L1, validated by proof
* @dev This function verifies if the transaction actually happened on child chain
*
* @param inputData RLP encoded data of the reference tx containing following list of fields
* 0 - headerNumber - Checkpoint header block number containing the reference tx
* 1 - blockProof - Proof that the block header (in the child chain) is a leaf in the submitted merkle root
* 2 - blockNumber - Block number containing the reference tx on child chain
* 3 - blockTime - Reference tx block time
* 4 - txRoot - Transactions root of block
* 5 - receiptRoot - Receipts root of block
* 6 - receipt - Receipt of the reference transaction
* 7 - receiptProof - Merkle proof of the reference receipt
* 8 - branchMask - 32 bits denoting the path of receipt in merkle tree
* 9 - receiptLogIndex - Log Index to read from the receipt
*/
function receiveMessage(bytes memory inputData) public virtual {
bytes memory message = _validateAndExtractMessage(inputData);
_processMessageFromChild(message);
}
/**
* @notice Process message received from Child Tunnel
* @dev function needs to be implemented to handle message as per requirement
* This is called by onStateReceive function.
* Since it is called via a system call, any event will not be emitted during its execution.
* @param message bytes message that was sent from Child Tunnel
*/
function _processMessageFromChild(bytes memory message) virtual internal;
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
/**
* @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 contracts/interfaces/IERC721.sol
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function mintBabyCrow() external;
function totalSupply() external view returns (uint256);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/utils/[email protected]
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721Holder is IERC721Receiver {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// File @openzeppelin/contracts/utils/[email protected]
/**
* @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/[email protected]
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File contracts/MadHouse.sol
contract MadHouse is ERC721Holder {}
// File contracts/Breeder.sol
/**
* @title Adds Breeding functionality to Crazy Crows Chess Club
* @author crispymangoes
* @notice Interacts with egg carton contract on polygon using Polygon State Transfer
*/
contract Breeder is FxBaseRootTunnel, ERC721Holder, Ownable {
IERC721 CrowsContract;
address public madhouse;
bytes32 public constant MAKE_EGG = keccak256("MAKE_EGG");
bytes32 public constant FIND_TRAITS = keccak256("FIND_TRAITS");
mapping(uint256 => uint256) public breedingTimeStamp;
uint256 public bonusCoolDown = 604800;
uint256 public baseCoolDown = 2419200;
bool public matingSeason;
bool public eggCreation = false;
bool public madHouseCreation = false;
/**
* @notice emitted when owner calls adminMint
* @param tokenID the token id of the newly minted crow
*/
event AdminCrowMint(uint256 tokenID);
constructor(
address _checkpointManager,
address _fxRoot,
address _fxERC721Token
) FxBaseRootTunnel(_checkpointManager, _fxRoot) {
CrowsContract = IERC721(_fxERC721Token);
madhouse = address(new MadHouse());
}
/****************** External onlyOwner Functions ******************/
/**
* @notice used by owner to set the cool down times for egg breeding
* @param _bonus how many seconds a crow needs to wait during mating season
* @param _base how many seconds a crow needs to wait normally
*/
function changeCoolDowns(uint256 _bonus, uint256 _base) external onlyOwner {
bonusCoolDown = _bonus;
baseCoolDown = _base;
}
/**
* @notice allows owner to turn egg breeding on and off
* @notice any previously existing eggs are still hatchable and useable
* it will only stop creation of new eggs
*/
function changeEggCreation(bool state) external onlyOwner {
eggCreation = state;
}
/// @notice allows owner to turn mad house breeding on and off
function changeMadhouseBreedingState(bool state) external onlyOwner {
madHouseCreation = state;
}
/// @notice allows owner to toggle mating season
function changeMatingSeason(bool state) external onlyOwner {
matingSeason = state;
}
/**
* @notice allows owner to mint a crow
* @notice this will only be used to mint promotional crows for partnerships
* or to mint crows in the event of a logic error in CCCC breeding contracts
* @notice emits AdminCrowMint when called
*/
function adminMint() external onlyOwner {
uint256 tID = CrowsContract.totalSupply();
CrowsContract.mintBabyCrow();
CrowsContract.safeTransferFrom(address(this), msg.sender, tID);
emit AdminCrowMint(tID);
}
/****************** External State Changing Functions ******************/
/**
* @notice burns two crows and mints caller 1 new crow
* keeping the parents two rarest traits
* @dev minted crow is blank at the start, traits are set on polygon
* @dev caller must approve breeder to spend their mom and dad crows
*/
function admitToMadHouse(uint256 mom, uint256 dad) external {
require(madHouseCreation, "MadHouse breeding not allowed");
//Sends the parents to the mad house
CrowsContract.safeTransferFrom(msg.sender, madhouse, mom);
CrowsContract.safeTransferFrom(msg.sender, madhouse, dad);
//mint caller a baby crow
uint256 babyID = CrowsContract.totalSupply();
CrowsContract.mintBabyCrow();
//send baby crow to caller
CrowsContract.safeTransferFrom(address(this), msg.sender, babyID);
//send data to polygon so that traits can be stored on chain
bytes memory message = abi.encode(
FIND_TRAITS,
abi.encode(babyID, mom, dad)
);
_sendMessageToChild(message);
}
/**
* @notice take two crows and create an egg
* @notice egg can be hatched using DeFi nests
* @notice Eggs live on polygon
* @dev caller must own mom and dad, and mom and dad must be able to breed
* @param receiver the address you want the egg sent to on polygon
*/
function makeEgg(
address receiver,
uint256 mom,
uint256 dad
) external {
require(eggCreation, "Egg Creation not allowed");
//make sure mom and dad can breed
uint256 timestamp = block.timestamp;
if (matingSeason) {
require(
timestamp > (breedingTimeStamp[mom] + bonusCoolDown),
"Mom can not breed yet"
);
require(
timestamp > (breedingTimeStamp[dad] + bonusCoolDown),
"Dad can not breed yet"
);
} else {
require(
timestamp > (breedingTimeStamp[mom] + baseCoolDown),
"Mom can not breed yet"
);
require(
timestamp > (breedingTimeStamp[dad] + baseCoolDown),
"Dad can not breed yet"
);
}
//requires to make sure caller owns mom and dad
require(
CrowsContract.ownerOf(mom) == msg.sender,
"Caller does not own mom"
);
require(
CrowsContract.ownerOf(dad) == msg.sender,
"Caller does not own dad"
);
breedingTimeStamp[mom] = timestamp;
breedingTimeStamp[dad] = timestamp;
uint256 babyID = CrowsContract.totalSupply();
CrowsContract.mintBabyCrow();
bytes memory message = abi.encode(
MAKE_EGG,
abi.encode(receiver, babyID, mom, dad)
);
_sendMessageToChild(message);
}
/****************** Internal State Changing Functions ******************/
/**
* @notice callable by anyone, but egg is sent to whichever address called
* sendHatchedEggToMainnet on egg carton
*/
function _processMessageFromChild(bytes memory message) internal override {
(address caller, uint256 tID) = abi.decode(message, (address, uint256));
CrowsContract.safeTransferFrom(address(this), caller, tID);
}
} | * @dev Returns true if this contract implements the interface defined by `interfaceId`. See the corresponding to learn more about how these ids are created. This function call must use less than 30 000 gas./ File contracts/interfaces/IERC721.sol* @dev Required interface of an ERC721 compliant contract./ | interface IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function mintBabyCrow() external;
function totalSupply() external view returns (uint256);
}
| 2,445,789 | [
1,
1356,
638,
309,
333,
6835,
4792,
326,
1560,
2553,
635,
1375,
5831,
548,
8338,
2164,
326,
4656,
358,
16094,
1898,
2973,
3661,
4259,
3258,
854,
2522,
18,
1220,
445,
745,
1297,
999,
5242,
2353,
5196,
20546,
16189,
18,
19,
1387,
20092,
19,
15898,
19,
45,
654,
39,
27,
5340,
18,
18281,
225,
10647,
1560,
434,
392,
4232,
39,
27,
5340,
24820,
6835,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
467,
654,
39,
27,
5340,
353,
467,
654,
39,
28275,
288,
203,
565,
871,
12279,
12,
203,
3639,
1758,
8808,
628,
16,
203,
3639,
1758,
8808,
358,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
20412,
16,
203,
3639,
2254,
5034,
8808,
1147,
548,
203,
565,
11272,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
203,
3639,
1758,
8808,
3410,
16,
203,
3639,
1758,
8808,
3726,
16,
203,
3639,
1426,
20412,
203,
565,
11272,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
6617,
537,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
336,
31639,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
3726,
1769,
203,
203,
565,
445,
444,
23461,
1290,
1595,
12,
2867,
3726,
16,
1426,
389,
25990,
13,
3903,
31,
203,
203,
2
] |
./full_match/1/0x309fAe80fa90858508d475A2f94e3aa722E87ead/sources/0x0.sol | force Swap back if slippage issues. | function forceSwapBack() external onlyOwner {
require(
balanceOf(address(this)) >= swapTokensAtAmount,
"Can only swap when token amount is at or higher than restriction"
);
swapping = true;
swapBack();
swapping = false;
emit OwnerForcedSwapBack(block.timestamp);
}
| 16,441,082 | [
1,
5734,
12738,
1473,
309,
272,
3169,
2433,
8296,
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,
3639,
445,
2944,
12521,
2711,
1435,
3903,
1338,
5541,
288,
203,
5411,
2583,
12,
203,
7734,
11013,
951,
12,
2867,
12,
2211,
3719,
1545,
7720,
5157,
861,
6275,
16,
203,
7734,
315,
2568,
1338,
7720,
1347,
1147,
3844,
353,
622,
578,
10478,
2353,
9318,
6,
203,
5411,
11272,
203,
5411,
7720,
1382,
273,
638,
31,
203,
5411,
7720,
2711,
5621,
203,
5411,
7720,
1382,
273,
629,
31,
203,
5411,
3626,
16837,
1290,
3263,
12521,
2711,
12,
2629,
18,
5508,
1769,
203,
3639,
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
] |
./full_match/1/0x2E516a4Db7Cf86daBe7653A7E60Ca9a1f4E96910/sources/coshi/multiOwnable.sol | VARIABLES Reverse lookup tables for owners and allOperations Owners voting mask per operations EVENTS ACCESSORS | contract Multiownable {
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
mapping(bytes32 => uint) public allOperationsIndicies;
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
pragma solidity ^0.6.12;
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
allOperations.pop();
}
| 4,926,078 | [
1,
16444,
55,
18469,
3689,
4606,
364,
25937,
471,
777,
9343,
14223,
9646,
331,
17128,
3066,
1534,
5295,
9964,
55,
13255,
14006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5991,
995,
429,
288,
203,
203,
203,
565,
2254,
5034,
1071,
25937,
13842,
31,
203,
565,
2254,
5034,
1071,
3661,
5594,
5460,
414,
1799,
831,
31,
203,
565,
1758,
8526,
1071,
25937,
31,
203,
565,
1731,
1578,
8526,
1071,
777,
9343,
31,
203,
565,
1758,
2713,
4832,
1477,
12021,
31,
203,
565,
2254,
5034,
2713,
4832,
1477,
1380,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
13,
1071,
777,
9343,
3866,
335,
606,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
1071,
19588,
5796,
858,
2988,
31,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
1071,
19588,
1380,
858,
2988,
31,
203,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8526,
2416,
5460,
414,
16,
2254,
3661,
5594,
5460,
414,
1799,
831,
16,
1758,
8526,
394,
5460,
414,
16,
2254,
394,
44,
543,
5594,
5460,
414,
1799,
831,
1769,
203,
565,
871,
4189,
6119,
12,
3890,
1578,
1674,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
450,
5607,
1769,
203,
565,
871,
4189,
1211,
90,
16474,
12,
3890,
1578,
1674,
16,
2254,
19588,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
731,
90,
20005,
1769,
203,
565,
871,
4189,
13889,
12,
3890,
1578,
1674,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
3073,
264,
1769,
203,
565,
871,
4189,
4164,
90,
16474,
12,
3890,
1578,
1674,
16,
2254,
19588,
16,
2254,
25937,
1380,
16,
225,
1758,
2588,
90,
20005,
1769,
203,
565,
871,
4189,
21890,
12,
2
] |
pragma solidity ^0.4.18;
/**
* @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;
}
}
/**
* @title ERC721 interface
* @dev see https://github.com/ethereum/eips/issues/721
*/
contract ERC721 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 _tokenId
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function transfer(address _to, uint256 _tokenId) public;
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
}
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC721/ERC721Token.sol
/**
* @title ERC721Token
* Generic implementation for the required functionality of the ERC721 standard
*/
contract NFTKred is ERC721 {
using SafeMath for uint256;
// Public variables of the contract
string public name;
string public symbol;
// Most Ethereum contracts use 18 decimals, but we restrict it to 7 here
// for portability to and from Stellar.
uint8 public valueDecimals = 7;
// Numeric data
mapping(uint => uint) public nftBatch;
mapping(uint => uint) public nftSequence;
mapping(uint => uint) public nftCount;
// The face value of the NFT must be intrinsic so that smart contracts can work with it
// Sale price and last sale price are available via the metadata endpoints
mapping(uint => uint256) public nftValue;
// NFT strings - these are expensive to store, but necessary for API compatibility
// And string manipulation is also expensive
// Not to be confused with name(), which returns the contract name
mapping(uint => string) public nftName;
// The NFT type, e.g. coin, card, badge, ticket
mapping(uint => string) public nftType;
// API address of standard metadata
mapping(uint => string) public nftURIs;
// IPFS address of extended metadata
mapping(uint => string) public tokenIPFSs;
// Total amount of tokens
uint256 private totalTokens;
// Mapping from token ID to owner
mapping(uint256 => address) private tokenOwner;
// Mapping from token ID to approved address
mapping(uint256 => address) private tokenApprovals;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private ownedTokensIndex;
// Metadata accessors
function name() external view returns (string _name) {
return name;
}
function symbol() external view returns (string _symbol) {
return symbol;
}
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return nftURIs[_tokenId];
}
function tokenIPFS(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenIPFSs[_tokenId];
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
/* constructor( */
constructor(
string tokenName,
string tokenSymbol
) public {
name = tokenName;
// Set the name for display purposes
symbol = tokenSymbol;
// Set the symbol for display purposes
}
/**
* @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 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 totalTokens;
}
/**
* @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 ownedTokens[_owner].length;
}
/**
* @dev Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[]) {
return ownedTokens[_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 Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function approvedFor(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transfer(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) {
clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
/**
* @dev Approves another address to claim for the ownership of the given token ID
* @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 onlyOwnerOf(_tokenId) {
address owner = ownerOf(_tokenId);
require(_to != owner);
if (approvedFor(_tokenId) != 0 || _to != 0) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Claims the ownership of a given token ID
* @param _tokenId uint256 ID of the token being claimed by the msg.sender
*/
function takeOwnership(uint256 _tokenId) public {
require(isApprovedFor(msg.sender, _tokenId));
clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId);
}
// Mint an NFT - should this be a smart contract function dependent on CKr tokens?
function mint(
address _to,
uint256 _tokenId,
uint _batch,
uint _sequence,
uint _count,
uint256 _value,
string _type,
string _IPFS,
string _tokenURI
) public /* onlyNonexistentToken(_tokenId) */
{
// Addresses for direct test (Ethereum wallet) and live test (Geth server)
require(
msg.sender == 0x979e636D308E86A2D9cB9B2eA5986d6E2f89FcC1 ||
msg.sender == 0x0fEB00CAe329050915035dF479Ce6DBf747b01Fd
);
require(_to != address(0));
require(nftValue[_tokenId] == 0);
// Batch details - also available from the metadata endpoints
nftBatch[_tokenId] = _batch;
nftSequence[_tokenId] = _sequence;
nftCount[_tokenId] = _count;
// Value in CKr + 7 trailing zeroes (to reflect Stellar)
nftValue[_tokenId] = _value;
// Token type
nftType[_tokenId] = _type;
// Metadata access via IPFS (canonical URL)
tokenIPFSs[_tokenId] = _IPFS;
// Metadata access via API (canonical url - add /{platform} for custom-formatted data for your platform
nftURIs[_tokenId] = _tokenURI;
addToken(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a specific token
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(uint256 _tokenId) onlyOwnerOf(_tokenId) internal {
if (approvedFor(_tokenId) != 0) {
clearApproval(msg.sender, _tokenId);
}
removeToken(msg.sender, _tokenId);
emit Transfer(msg.sender, 0x0, _tokenId);
}
/**
* @dev Tells whether the msg.sender is approved for the given token ID or not
* This function is not private so it can be extended in further implementations like the operatable ERC721
* @param _owner address of the owner to query the approval of
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether the msg.sender is approved for the given token ID or not
*/
function isApprovedFor(address _owner, uint256 _tokenId) internal view returns (bool) {
return approvedFor(_tokenId) == _owner;
}
/**
* @dev Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
clearApproval(_from, _tokenId);
removeToken(_from, _tokenId);
addToken(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = 0;
emit Approval(_owner, 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 addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.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 removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = 0;
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;
totalTokens = totalTokens.sub(1);
}
/**
* @dev Returns `true` if the contract implements `interfaceID` and `interfaceID` is not 0xffffffff, `false` otherwise
* @param _interfaceID The interface identifier, as specified in ERC-165
*/
function supportsInterface(bytes4 _interfaceID) public pure returns (bool) {
if (_interfaceID == 0xffffffff) {
return false;
}
return _interfaceID == 0x01ffc9a7 || // From ERC721Base
_interfaceID == 0x7c0633c6 || // From ERC721Base
_interfaceID == 0x80ac58cd || // ERC721
_interfaceID == 0x5b5e139f; // ERC712Metadata
}
} | * @dev Internal function to clear current approval and transfer the ownership of a given token ID @param _from address which you want to send tokens from @param _to address which you want to transfer the token to @param _tokenId uint256 ID of the token to be transferred/ | function clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal {
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
clearApproval(_from, _tokenId);
removeToken(_from, _tokenId);
addToken(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
| 12,638,929 | [
1,
3061,
445,
358,
2424,
783,
23556,
471,
7412,
326,
23178,
434,
279,
864,
1147,
1599,
225,
389,
2080,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1492,
1846,
2545,
358,
7412,
326,
1147,
358,
225,
389,
2316,
548,
2254,
5034,
1599,
434,
326,
1147,
358,
506,
906,
4193,
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,
2424,
23461,
1876,
5912,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
2316,
548,
13,
2713,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
24899,
869,
480,
3410,
951,
24899,
2316,
548,
10019,
203,
3639,
2583,
12,
8443,
951,
24899,
2316,
548,
13,
422,
389,
2080,
1769,
203,
203,
3639,
2424,
23461,
24899,
2080,
16,
389,
2316,
548,
1769,
203,
3639,
1206,
1345,
24899,
2080,
16,
389,
2316,
548,
1769,
203,
3639,
527,
1345,
24899,
869,
16,
389,
2316,
548,
1769,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
2316,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xcF9C5EA1373f233F323156C2249662Cf9c60386d/sources/contracts/EURSToken.sol | * Get address of message sender. @return address of this smart contract/ | function messageSenderAddress () internal virtual view returns (address) {
return msg.sender;
}
| 755,081 | [
1,
967,
1758,
434,
883,
5793,
18,
327,
1758,
434,
333,
13706,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
883,
12021,
1887,
1832,
2713,
5024,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
1234,
18,
15330,
31,
203,
225,
289,
203,
203,
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
] |
//Address: 0x34eee0379a71e445b0dc52bda1d733c449ef1246
//Contract name: hotPotatoAuction
//Balance: 0.154873437500000028 Ether
//Verification Date: 6/18/2018
//Transacion Count: 12
// CODE STARTS HERE
pragma solidity ^0.4.21;
// Contract for Auction of the starship Astra Kal
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;
}
}
// This is an interface which creates a symbol for the starships ERC721 contracts.
// The ERC721 contracts will be published later, before the auction ends.
contract starShipTokenInterface {
string public name;
string public symbol;
uint256 public ID;
address public owner;
function transfer(address _to) public returns (bool success);
event Transfer(address indexed _from, address indexed _to);
}
contract starShipToken is starShipTokenInterface {
using SafeMath for uint256;
constructor(string _name, string _symbol, uint256 _ID) public {
name = _name;
symbol = _symbol;
ID = _ID;
owner = msg.sender;
}
/**
* @dev Gets the owner of the token.
* @return An uint256 representing the amount owned by the passed address.
*/
function viewOwner() public view returns (address) {
return owner;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
*/
function transfer(address _to) public returns (bool) {
require(_to != address(0));
require(msg.sender == owner);
owner = _to;
emit Transfer(msg.sender, _to);
return true;
}
}
// contract for implementing the auction in Hot Potato format
contract hotPotatoAuction {
// The token that is going up for auction
starShipToken public token;
// The total number of bids on the current starship
uint256 public totalBids;
// starting bid of the starship
uint256 public startingPrice;
// current Bid amount
uint256 public currentBid;
// Minimum amount needed to bid on this item
uint256 public currentMinBid;
// The time at which the auction will end
uint256 public auctionEnd;
// Variable to store the hot Potato prize for the loser bid
uint256 public hotPotatoPrize;
// The seller of the current item
address public seller;
address public highBidder;
address public loser;
function hotPotatoAuction(
starShipToken _token,
uint256 _startingPrice,
uint256 _auctionEnd
)
public
{
token = _token;
startingPrice = _startingPrice;
currentMinBid = _startingPrice;
totalBids = 0;
seller = msg.sender;
auctionEnd = _auctionEnd;
hotPotatoPrize = _startingPrice;
currentBid = 0;
}
mapping(address => uint256) public balanceOf;
/**
* @dev withdrawBalance from the contract address
* @param amount that you want to withdrawBalance
*
*/
function withdrawBalance(uint256 amount) returns(bool) {
require(amount <= address(this).balance);
require (msg.sender == seller);
seller.transfer(amount);
return true;
}
/**
* @dev withdraw from the Balance array
*
*/
function withdraw() public returns(bool) {
require(msg.sender != highBidder);
uint256 amount = balanceOf[loser];
balanceOf[loser] = 0;
loser.transfer(amount);
return true;
}
event Bid(address highBidder, uint256 highBid);
function bid() public payable returns(bool) {
require(now < auctionEnd);
require(msg.value >= startingPrice);
require (msg.value >= currentMinBid);
if(totalBids !=0)
{
loser = highBidder;
require(withdraw());
}
highBidder = msg.sender;
currentBid = msg.value;
hotPotatoPrize = currentBid/20;
balanceOf[msg.sender] = msg.value + hotPotatoPrize;
if(currentBid < 1000000000000000000)
{
currentMinBid = msg.value + currentBid/2;
hotPotatoPrize = currentBid/20;
}
else
{
currentMinBid = msg.value + currentBid/5;
hotPotatoPrize = currentBid/20;
}
totalBids = totalBids + 1;
return true;
emit Bid(highBidder, msg.value);
}
function resolve() public {
require(now >= auctionEnd);
require(msg.sender == seller);
require (highBidder != 0);
require (token.transfer(highBidder));
balanceOf[seller] += balanceOf[highBidder];
balanceOf[highBidder] = 0;
highBidder = 0;
}
/**
* @dev view balance of contract
*/
function getBalanceContract() constant returns(uint){
return address(this).balance;
}
}
| * @dev transfer token for a specified address @param _to The address to transfer to./ | function transfer(address _to) public returns (bool) {
require(_to != address(0));
require(msg.sender == owner);
owner = _to;
emit Transfer(msg.sender, _to);
return true;
}
| 12,694,307 | [
1,
13866,
1147,
364,
279,
1269,
1758,
225,
389,
869,
1021,
1758,
358,
7412,
358,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
7412,
12,
2867,
389,
869,
13,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
565,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
203,
565,
3410,
273,
389,
869,
31,
203,
565,
3626,
12279,
12,
3576,
18,
15330,
16,
389,
869,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
// import '@nomiclabs/buidler/console.sol';
import "./ERC1155.sol";
import "./IERC1155Views.sol";
contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
// See also _createSwapLimit()
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
int timeEnteredSwapCredit; // zero means not in a swap credit
int lastSwapTime; // ignored when not in a swap credit
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
// IERC1155Views
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
// Administrativia
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
// Intentially no setTokenName() and setTokenSymbol()
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
// We don't check for circularities.
function setTokenParent(uint256 _child, uint256 _parent) external {
// require(_child != 0 && _child <= maxTokenId); // not needed
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
// Each element of `_childs` list must be a child of the next one.
// TODO: Test. Especially test the case if the last child has no parent. Also test if a child is zero.
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint256 _firstChild = _childs[0]; // asserts on `_childs.length == 0`.
bool _hasRight = false; // if msg.sender is an ancestor
// Note that if in the below loops we disable ourselves, then it will be detected by a require
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
// We are not msg.sender
tokenFlow[_id].enabled = _enabled; // cannot enable for msg.sender
++i;
}
require(_hasRight);
}
// User can set negative values. It is a nonsense but does not harm.
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// User can set negative values. It is a nonsense but does not harm.
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// ERC-1155
// A token can anyway change its parent at any moment, so disabling of payments makes no sense.
// function safeTransferFrom(
// address _from,
// address _to,
// uint256 _id,
// uint256 _value,
// bytes calldata _data) external virtual override
// {
// require(tokenFlow[_id].enabled);
// super._safeTransferFrom(_from, _to, _id, _value, _data);
// }
// function safeBatchTransferFrom(
// address _from,
// address _to,
// uint256[] calldata _ids,
// uint256[] calldata _values,
// bytes calldata _data) external virtual override
// {
// for (uint i = 0; i < _ids.length; ++i) {
// require(tokenFlow[_ids[i]].enabled);
// }
// super._safeBatchTransferFrom(_from, _to, _ids, _values, _data);
// }
// Misc
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check overflow due to previous line
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Flow
// Each next token ID must be a parent of the previous one.
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
// Intentionally no check for `msg.sender`.
require(_ids[_ids.length - 1] != 0); // The rest elements are checked below.
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
require(_parent == _ids[i + 1]); // i ranges 0 .. _ids.length - 2
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
} else {
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
_flow.lastSwapTime = _currentTimeResult; // TODO: no strictly necessary if !_flow.recurring
// require(_amount < 1<<128); // done above
_flow.remainingSwapCredit -= int256(_amount);
}
// if (_id == _flow.parentToken) return; // not necessary
_doBurn(msg.sender, _ids[0], _amount);
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
// Each next token ID must be a parent of the previous one.
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
require(_parent == _ids[i]); // consequently `_ids[i] != 0`
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
// Internal
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
balances[_id][_to] += _value; // no need to check for overflow due to the previous line
}
// MUST emit event
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
// require(_from != address(0), "_from must be non-zero.");
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check for overflow due to the previous line
// MUST emit event
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Also resets swap credits and `enabled`, so use with caution.
// Allow this even if `!enabled` and set `enabled` to `true` if no parent,
// as otherwise impossible to enable it again.
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
timeEnteredSwapCredit: 0, // zero means not in a swap credit
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
// solhint-disable indent
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
} else {
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
// Events
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
| We don't check for circularities. require(_child != 0 && _child <= maxTokenId); not needed | function setTokenParent(uint256 _child, uint256 _parent) external {
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
| 1,073,095 | [
1,
3218,
2727,
1404,
866,
364,
15302,
1961,
18,
2583,
24899,
3624,
480,
374,
597,
389,
3624,
1648,
943,
1345,
548,
1769,
225,
486,
3577,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22629,
3054,
12,
11890,
5034,
389,
3624,
16,
2254,
5034,
389,
2938,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1147,
5460,
414,
63,
67,
3624,
19226,
203,
203,
3639,
389,
542,
1345,
3054,
2279,
1564,
24899,
3624,
16,
389,
2938,
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
] |
./full_match/1/0x1a8C505792e267B3C3b92aBe0BC791a61A0ede90/sources/contracts/vesting/StablzVesting.sol | @notice Import vesting data @param _addresses List of addresses @param _amounts List of amounts @param _tgePercent TGE percentage e.g. 20 is 20% @param _vestingPeriod Vesting period in seconds e.g. 2592000 is 30 days | function importData(address[] calldata _addresses, uint[] calldata _amounts, uint _tgePercent, uint _vestingPeriod) external onlyOwner {
require(!_hasVestingStarted(), "StablzVesting: Cannot import data after vesting has started");
require(_addresses.length == _amounts.length, "StablzVesting: _addresses and _amounts list lengths do not match");
require(_tgePercent < TGE_PERCENT_DENOMINATOR, "StablzVesting: _tgePercent must be less than 100");
uint total;
for (uint i; i < _addresses.length; i++) {
total += _amounts[i];
User storage user = _users[_addresses[i]];
uint tgeAmount;
if (_tgePercent > 0) {
tgeAmount = _amounts[i] * _tgePercent / TGE_PERCENT_DENOMINATOR;
}
uint vested = _amounts[i] - tgeAmount;
user.vestments[user.numberOfVestments] = Vestment(
vested,
0,
_vestingPeriod,
tgeAmount,
false
);
user.numberOfVestments++;
}
totalAmount += total;
}
| 9,818,956 | [
1,
5010,
331,
10100,
501,
225,
389,
13277,
987,
434,
6138,
225,
389,
8949,
87,
987,
434,
30980,
225,
389,
88,
908,
8410,
399,
7113,
11622,
425,
18,
75,
18,
4200,
353,
4200,
9,
225,
389,
90,
10100,
5027,
776,
10100,
3879,
316,
3974,
425,
18,
75,
18,
576,
6162,
17172,
353,
5196,
4681,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1930,
751,
12,
2867,
8526,
745,
892,
389,
13277,
16,
2254,
8526,
745,
892,
389,
8949,
87,
16,
2254,
389,
88,
908,
8410,
16,
2254,
389,
90,
10100,
5027,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
5,
67,
5332,
58,
10100,
9217,
9334,
315,
510,
9237,
94,
58,
10100,
30,
14143,
1930,
501,
1839,
331,
10100,
711,
5746,
8863,
203,
3639,
2583,
24899,
13277,
18,
2469,
422,
389,
8949,
87,
18,
2469,
16,
315,
510,
9237,
94,
58,
10100,
30,
389,
13277,
471,
389,
8949,
87,
666,
10917,
741,
486,
845,
8863,
203,
3639,
2583,
24899,
88,
908,
8410,
411,
399,
7113,
67,
3194,
19666,
67,
13296,
1872,
706,
3575,
16,
315,
510,
9237,
94,
58,
10100,
30,
389,
88,
908,
8410,
1297,
506,
5242,
2353,
2130,
8863,
203,
3639,
2254,
2078,
31,
203,
3639,
364,
261,
11890,
277,
31,
277,
411,
389,
13277,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2078,
1011,
389,
8949,
87,
63,
77,
15533,
203,
5411,
2177,
2502,
729,
273,
389,
5577,
63,
67,
13277,
63,
77,
13563,
31,
203,
203,
5411,
2254,
268,
908,
6275,
31,
203,
5411,
309,
261,
67,
88,
908,
8410,
405,
374,
13,
288,
203,
7734,
268,
908,
6275,
273,
389,
8949,
87,
63,
77,
65,
380,
389,
88,
908,
8410,
342,
399,
7113,
67,
3194,
19666,
67,
13296,
1872,
706,
3575,
31,
203,
5411,
289,
203,
5411,
2254,
331,
3149,
273,
389,
8949,
87,
63,
77,
65,
300,
268,
908,
6275,
31,
203,
5411,
729,
18,
26923,
1346,
2
] |
pragma solidity ^0.4.18;
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/issues/20
contract ERC20Interface {
/// @notice Get the total metadollars supply
function totalSupply() constant returns (uint256 totalAmount);
/// @notice Get the account balance of another account with address _owner
function balanceOf(address _owner) constant returns (uint256 balance);
/// @notice Send _value amount of metadollarss to address _to
function transfer(address _to, uint256 _value) returns (bool success);
/// @notice Send _value amount of metadollars from address _from to address _to
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
/// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
/// @notice this function is required for some DEX functionality
function approve(address _spender, uint256 _value) returns (bool success);
/// @notice Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
/// @notice Triggered when metadollars are transferred.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @notice Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract owned{
address public owner;
address constant supervisor = 0x2d6808bC989CbEB46cc6dd75a6C90deA50e3e504;
function owned(){
owner = msg.sender;
}
/// @notice Functions with this modifier can only be executed by the owner
modifier isOwner {
assert(msg.sender == owner || msg.sender == supervisor);
_;
}
/// @notice Transfer the ownership of this contract
function transferOwnership(address newOwner);
event ownerChanged(address whoTransferredOwnership, address formerOwner, address newOwner);
}
contract METADOLLAR is ERC20Interface, owned{
string public constant name = "METADOLLAR";
string public constant symbol = "DOL";
uint public constant decimals = 18;
uint256 public _totalSupply = 1000000000000000000000000000000; // Total Supply 1000,000,000,000
uint256 public icoMin = 1000000000000000000000000000000; // Min ICO 1000,000,000,000
uint256 public preIcoLimit = 1000000000000000000; // Pre Ico Limit 1
uint256 public countHolders = 0; // count how many unique holders have metadollars
uint256 public amountOfInvestments = 0; // amount of collected wei
uint256 public preICOprice; // price of 1 metadollar in weis for the preICO time
uint256 public ICOprice; // price of 1 metadollar in weis for the ICO time
uint256 public currentTokenPrice; // current metadollar price in weis
uint256 public sellPrice; // buyback price of one metadollar in weis
uint256 public buyRate; // Commission on buy
uint256 public sellRate; // Commission on sell
bool public preIcoIsRunning;
bool public minimalGoalReached;
bool public icoIsClosed;
bool icoExitIsPossible;
//Balances for each account
mapping (address => uint256) public tokenBalanceOf;
// Owner of account approves the transfer of an amount to another account
mapping(address => mapping (address => uint256)) allowed;
//list with information about frozen accounts
mapping(address => bool) frozenAccount;
//this generate a public event on a blockchain that will notify clients
event FrozenFunds(address initiator, address account, string status);
//this generate a public event on a blockchain that will notify clients
event BonusChanged(uint8 bonusOld, uint8 bonusNew);
//this generate a public event on a blockchain that will notify clients
event minGoalReached(uint256 minIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event preIcoEnded(uint256 preIcoAmount, string notice);
//this generate a public event on a blockchain that will notify clients
event priceUpdated(uint256 oldPrice, uint256 newPrice, string notice);
//this generate a public event on a blockchain that will notify clients
event withdrawed(address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event deposited(address _from, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event orderToTransfer(address initiator, address _from, address _to, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenCreated(address _creator, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event tokenDestroyed(address _destroyer, uint256 summe, string notice);
//this generate a public event on a blockchain that will notify clients
event icoStatusUpdated(address _initiator, string status);
/// @notice Constructor of the contract
function STARTMETADOLLAR() {
preIcoIsRunning = true;
minimalGoalReached = false;
icoExitIsPossible = false;
icoIsClosed = false;
tokenBalanceOf[this] += _totalSupply;
allowed[this][owner] = _totalSupply;
allowed[this][supervisor] = _totalSupply;
currentTokenPrice = 1 * 1 ether; // initial price of 1 metadollar
preICOprice = 1000000000000000000 * 1000000000000000000 wei; // price of 1 token in weis for the preICO time, ca.6,- Euro
ICOprice = 1000000000000000000 * 1000000000000000000 wei; // price of 1 token in weis for the ICO time, ca.10,- Euro
sellPrice = 1000000000000000000 * 1000000000000000000 wei;
buyRate = 0; // set 100 for 1% or 1000 for 0.1%
sellRate = 0; // set 100 for 1% or 1000 for 0.1%
updatePrices();
}
function () payable {
require(!frozenAccount[msg.sender]);
if(msg.value > 0 && !frozenAccount[msg.sender]) {
buyToken();
}
}
/// @notice Returns a whole amount of metadollars
function totalSupply() constant returns (uint256 totalAmount) {
totalAmount = _totalSupply;
}
/// @notice What is the balance of a particular account?
function balanceOf(address _owner) constant returns (uint256 balance) {
return tokenBalanceOf[_owner];
}
/// @notice Shows how much metadollars _spender can spend from _owner address
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice Calculates amount of weis needed to buy more than one metadollar
/// @param howManyTokenToBuy - Amount of metadollars to calculate
function calculateTheEndPrice(uint256 howManyTokenToBuy) constant returns (uint256 summarizedPriceInWeis) {
if(howManyTokenToBuy > 0) {
summarizedPriceInWeis = howManyTokenToBuy * currentTokenPrice;
}else {
summarizedPriceInWeis = 0;
}
}
/// @notice Shows if account is frozen
/// @param account - Accountaddress to check
function checkFrozenAccounts(address account) constant returns (bool accountIsFrozen) {
accountIsFrozen = frozenAccount[account];
}
/// @notice Buy metadollars from contract by sending ether
function buy() payable public {
require(!frozenAccount[msg.sender]);
require(msg.value > 0);
uint commission = msg.value/buyRate; // Buy Commission x1000 of wei tx
require(address(this).send(commission));
buyToken();
}
/// @notice Sell metadollars and receive ether from contract
function sell(uint256 amount) {
require(!frozenAccount[msg.sender]);
require(tokenBalanceOf[msg.sender] >= amount); // checks if the sender has enough to sell
require(amount > 0);
require(sellPrice > 0);
_transfer(msg.sender, this, amount);
uint256 revenue = amount * sellPrice;
uint commission = msg.value/sellRate; // Sell Commission x1000 of wei tx
require(address(this).send(commission));
msg.sender.transfer(revenue); // sends ether to the seller: it's important to do this last to prevent recursion attacks
}
/// @notice Allow user to sell all amount of metadollars at once , depend on ether amount on contract
function sellAllDolAtOnce() {
require(!frozenAccount[msg.sender]);
require(tokenBalanceOf[msg.sender] > 0);
require(this.balance > sellPrice);
if(tokenBalanceOf[msg.sender] * sellPrice <= this.balance) {
sell(tokenBalanceOf[msg.sender]);
}else {
sell(this.balance / sellPrice);
}
}
/// @notice Transfer amount of metadollars from own wallet to someone else
function transfer(address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[msg.sender] >= _value);
require(tokenBalanceOf[msg.sender] - _value < tokenBalanceOf[msg.sender]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
_transfer(msg.sender, _to, _value);
return true;
}
/// @notice Send _value amount of metadollars from address _from to address _to
/// @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send
/// @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge
/// @notice fees in sub-currencies; the command should fail unless the _from account has
/// @notice deliberately authorized the sender of the message via some mechanism; we propose
/// @notice these standardized APIs for approval:
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
assert(msg.sender != address(0));
assert(_from != address(0));
assert(_to != address(0));
require(!frozenAccount[msg.sender]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
require(tokenBalanceOf[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(tokenBalanceOf[_from] - _value < tokenBalanceOf[_from]);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(_value > 0);
orderToTransfer(msg.sender, _from, _to, _value, "Order to transfer metadollars from allowed account");
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
return true;
}
/// @notice Allow _spender to withdraw from your account, multiple times, up to the _value amount.
/// @notice If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
assert(_spender != address(0));
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
return true;
}
/// @notice Check if minimal goal of ICO is reached
function checkMinimalGoal() internal {
if(tokenBalanceOf[this] <= _totalSupply - icoMin) {
minimalGoalReached = true;
minGoalReached(icoMin, "Minimal goal of ICO is reached!");
}
}
/// @notice Check if preICO is ended
function checkPreIcoStatus() internal {
if(tokenBalanceOf[this] <= _totalSupply - preIcoLimit) {
preIcoIsRunning = false;
preIcoEnded(preIcoLimit, "Token amount for preICO sold!");
}
}
/// @notice Processing each buying
function buyToken() internal {
uint256 value = msg.value;
address sender = msg.sender;
require(!icoIsClosed);
require(!frozenAccount[sender]);
require(value > 0);
require(currentTokenPrice > 0);
uint256 amount = value / currentTokenPrice; // calculates amount of metadollars
uint256 moneyBack = value - (amount * currentTokenPrice);
require(tokenBalanceOf[this] >= amount); // checks if contract has enough to sell
amountOfInvestments = amountOfInvestments + (value - moneyBack);
updatePrices();
_transfer(this, sender, amount);
if(!minimalGoalReached) {
checkMinimalGoal();
}
if(moneyBack > 0) {
sender.transfer(moneyBack);
}
}
/// @notice Internal transfer, can only be called by this contract
function _transfer(address _from, address _to, uint256 _value) internal {
assert(_from != address(0));
assert(_to != address(0));
require(_value > 0);
require(tokenBalanceOf[_from] >= _value);
require(tokenBalanceOf[_to] + _value > tokenBalanceOf[_to]);
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
if(tokenBalanceOf[_to] == 0){
countHolders += 1;
}
tokenBalanceOf[_from] -= _value;
if(tokenBalanceOf[_from] == 0){
countHolders -= 1;
}
tokenBalanceOf[_to] += _value;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
Transfer(_from, _to, _value);
}
/// @notice Set current ICO prices in wei for one metadollar
function updatePrices() internal {
uint256 oldPrice = currentTokenPrice;
if(preIcoIsRunning) {
checkPreIcoStatus();
}
if(preIcoIsRunning) {
currentTokenPrice = preICOprice;
}else{
currentTokenPrice = ICOprice;
}
if(oldPrice != currentTokenPrice) {
priceUpdated(oldPrice, currentTokenPrice, "Metadollar price updated!");
}
}
/// @notice Set current preICO price in wei for one metadollar
/// @param priceForPreIcoInWei - is the amount in wei for one metadollar
function setPreICOPrice(uint256 priceForPreIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(preICOprice != priceForPreIcoInWei);
preICOprice = priceForPreIcoInWei;
updatePrices();
}
/// @notice Set current ICO price price in wei for one metadollar
/// @param priceForIcoInWei - is the amount in wei
function setICOPrice(uint256 priceForIcoInWei) isOwner {
require(priceForIcoInWei > 0);
require(ICOprice != priceForIcoInWei);
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set both prices at the same time
/// @param priceForPreIcoInWei - Price of the metadollar in pre ICO
/// @param priceForIcoInWei - Price of the metadollar in ICO
function setPrices(uint256 priceForPreIcoInWei, uint256 priceForIcoInWei) isOwner {
require(priceForPreIcoInWei > 0);
require(priceForIcoInWei > 0);
preICOprice = priceForPreIcoInWei;
ICOprice = priceForIcoInWei;
updatePrices();
}
/// @notice Set the current sell price in wei for one metadollar
/// @param priceInWei - is the amount in wei for one metadollar
function setSellPrice(uint256 priceInWei) isOwner {
require(priceInWei >= 0);
sellPrice = priceInWei;
}
/// @notice Set current Buy Commission price in wei
/// @param buyRateInWei - is the amount in wei
function setBuyRate(uint256 buyRateInWei) isOwner {
require(buyRateInWei > 0);
require(buyRate != buyRateInWei);
buyRate = buyRateInWei;
updatePrices();
}
/// @notice Set current Sell Commission price in wei for one metadollar
/// @param sellRateInWei - is the amount in wei for one metadollar
function setSellRate(uint256 sellRateInWei) isOwner {
require(sellRateInWei > 0);
require(sellRate != sellRateInWei);
buyRate = sellRateInWei;
updatePrices();
}
/// @notice Set both commissions at the same time
/// @param buyRateInWei - Commission for buy
/// @param sellRateInWei - Commission for sell
function setRates(uint256 buyRateInWei, uint256 sellRateInWei) isOwner {
require( buyRateInWei> 0);
require(sellRateInWei > 0);
buyRate = buyRateInWei;
sellRate = buyRateInWei;
updatePrices();
}
/// @notice 'freeze? Prevent | Allow' 'account' from sending and receiving metadollars
/// @param account - address to be frozen
/// @param freeze - select is the account frozen or not
function freezeAccount(address account, bool freeze) isOwner {
require(account != owner);
require(account != supervisor);
frozenAccount[account] = freeze;
if(freeze) {
FrozenFunds(msg.sender, account, "Account set frozen!");
}else {
FrozenFunds(msg.sender, account, "Account set free for use!");
}
}
/// @notice Create an amount of metadollars
/// @param amount - metadollars to create
function mintToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] <= icoMin); // owner can create metadollars only if the initial amount is strongly not enough to supply and demand ICO
require(_totalSupply + amount > _totalSupply);
require(tokenBalanceOf[this] + amount > tokenBalanceOf[this]);
_totalSupply += amount;
tokenBalanceOf[this] += amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenCreated(msg.sender, amount, "Additional metadollars created!");
}
/// @notice Destroy an amount of metadollars
/// @param amount - token to destroy
function destroyToken(uint256 amount) isOwner {
require(amount > 0);
require(tokenBalanceOf[this] >= amount);
require(_totalSupply >= amount);
require(tokenBalanceOf[this] - amount >= 0);
require(_totalSupply - amount >= 0);
tokenBalanceOf[this] -= amount;
_totalSupply -= amount;
allowed[this][owner] = tokenBalanceOf[this];
allowed[this][supervisor] = tokenBalanceOf[this];
tokenDestroyed(msg.sender, amount, "An amount of metadollars destroyed!");
}
/// @notice Transfer the ownership to another account
/// @param newOwner - address who get the ownership
function transferOwnership(address newOwner) isOwner {
assert(newOwner != address(0));
address oldOwner = owner;
owner = newOwner;
ownerChanged(msg.sender, oldOwner, newOwner);
allowed[this][oldOwner] = 0;
allowed[this][newOwner] = tokenBalanceOf[this];
}
/// @notice Transfer ether from smartcontract to owner
function collect() isOwner {
require(this.balance > 0);
withdraw(this.balance);
}
/// @notice Withdraw an amount of ether
/// @param summeInWei - amout to withdraw
function withdraw(uint256 summeInWei) isOwner {
uint256 contractbalance = this.balance;
address sender = msg.sender;
require(contractbalance >= summeInWei);
withdrawed(sender, summeInWei, "wei withdrawed");
sender.transfer(summeInWei);
}
/// @notice Deposit an amount of ether
function deposit() payable isOwner {
require(msg.value > 0);
require(msg.sender.balance >= msg.value);
deposited(msg.sender, msg.value, "wei deposited");
}
/// @notice Allow user to exit ICO
/// @param exitAllowed - status if the exit is allowed
function allowIcoExit(bool exitAllowed) isOwner {
require(icoExitIsPossible != exitAllowed);
icoExitIsPossible = exitAllowed;
}
/// @notice Stop running ICO
/// @param icoIsStopped - status if this ICO is stopped
function stopThisIco(bool icoIsStopped) isOwner {
require(icoIsClosed != icoIsStopped);
icoIsClosed = icoIsStopped;
if(icoIsStopped) {
icoStatusUpdated(msg.sender, "Coin offering was stopped!");
}else {
icoStatusUpdated(msg.sender, "Coin offering is running!");
}
}
} | price of 1 metadollar in weis for the ICO time
| uint256 public ICOprice; | 14,541,625 | [
1,
8694,
434,
404,
312,
1167,
25442,
316,
732,
291,
364,
326,
467,
3865,
813,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
11890,
5034,
1071,
26899,
3817,
3057,
31,
6862,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/**
* @title Wicked Wepz ERC-721 token contract.
* @author Josh Stow (https://github.com/jshstw)
*/
contract WickedWepz is ERC721Enumerable, Ownable, Pausable {
using SafeMath for uint256;
using Address for address payable;
uint256 public constant WWz_RESERVED = 10;
uint256 public constant WWz_MAX = 1000;
uint256 public constant WWz_PRICE = 0.04 ether;
uint256 public constant WWz_MAX_PER_TX = 20;
string private _baseTokenURI;
bool public saleLive;
constructor(string memory newBaseTokenURI)
ERC721("Wicked Wepz", "WWz")
{
_baseTokenURI = newBaseTokenURI;
}
/**
* @dev Mints number of tokens specified to wallet.
* @param quantity uint256 Number of tokens to be minted
*/
function buy(uint256 quantity) external payable whenNotPaused {
require(saleLive, "WickedWepz: Sale is not currently live");
require(totalSupply() <= ((WWz_MAX - WWz_RESERVED) - quantity), "WickedWepz: Quantity exceeds remaining tokens");
require(quantity <= WWz_MAX_PER_TX, "WickedWepz: Quantity exceeds max per transaction");
require(quantity != 0, "WickedWepz: Cannot buy zero tokens");
require(msg.value >= (quantity * WWz_PRICE), "WickedWepz: Insufficient funds");
for (uint256 i=0; i<quantity; i++) {
_safeMint(msg.sender, totalSupply().add(1));
}
}
/**
* @dev Mint reserved tokens to owner's wallet after sale is finished.
*/
function claimReserved() public onlyOwner {
require(totalSupply() == WWz_MAX, "WickedWepzFactory: Token sale in progress");
for (uint256 i=0; i<WWz_RESERVED; i++) {
_safeMint(msg.sender, totalSupply().add(1));
}
}
/**
* @dev Returns token URI of token with given tokenId.
* @param tokenId uint256 Id of token
* @return string Specific token URI
*/
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), "KrubberDuckiez: URI query for nonexistent token");
return string(abi.encodePacked(_baseTokenURI, Strings.toString(tokenId)));
}
/**
* @dev Toggles status of token sale. Only callable by owner.
*/
function toggleSale() external onlyOwner {
saleLive = !saleLive;
}
/**
* @dev Withdraw funds from contract. Only callable by owner.
*/
function withdraw() public onlyOwner {
payable(msg.sender).sendValue(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../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 "../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);
}
} | * @dev Withdraw funds from contract. Only callable by owner./ | function withdraw() public onlyOwner {
payable(msg.sender).sendValue(address(this).balance);
}
| 1,538,714 | [
1,
1190,
9446,
284,
19156,
628,
6835,
18,
5098,
4140,
635,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
1435,
1071,
1338,
5541,
288,
203,
565,
8843,
429,
12,
3576,
18,
15330,
2934,
4661,
620,
12,
2867,
12,
2211,
2934,
12296,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.10;
// Miners create Elixor (EXOR), which they then convert to Elixir (ELIX)
contract elixor {
string public name;
string public symbol;
uint8 public decimals;
uint256 public startTime;
uint256 public totalSupply;
bool public balanceImportsComplete;
mapping (address => bool) public numRewardsAvailableSetForChildAddress;
mapping (address => bool) public isNewParent;
mapping (address => address) public returnChildForParentNew;
bool public genesisImportsComplete;
// Until contract is locked, devs can freeze the system if anything arises.
// Then deploy a contract that interfaces with the state of this one.
bool public frozen;
bool public freezeProhibited;
address public devAddress; // For doing imports
bool importsComplete; // Locked when devs have updated all balances
mapping (address => uint256) public burnAmountAllowed;
mapping(address => mapping (address => uint256)) allowed;
// Balances for each account
mapping(address => uint256) balances;
mapping (address => uint256) public numRewardsAvailable;
// ELIX address info
bool public ELIXAddressSet;
address public ELIXAddress;
event Transfer(address indexed from, address indexed to, uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function elixor() {
name = "elixor";
symbol = "EXOR";
decimals = 18;
startTime=1500307354; //Time contract went online.
devAddress=0x85196Da9269B24bDf5FfD2624ABB387fcA05382B; // Set the dev import address
// Dev will create 10 batches as test using 1 EXOR in dev address (which is a child)
// Also will send tiny amounts to several random addresses to make sure parent-child auth works.
// Then set numRewardsAvailable to 0
balances[devAddress]+=1000000000000000000;
totalSupply+=1000000000000000000;
numRewardsAvailableSetForChildAddress[devAddress]=true;
numRewardsAvailable[devAddress]=10;
}
// Returns balance of particular account
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) {
if (!frozen){
if (balances[msg.sender] < _value) revert();
if (balances[_to] + _value < balances[_to]) revert();
if (returnIsParentAddress(_to) || isNewParent[_to]) {
if ((msg.sender==returnChildAddressForParent(_to)) || (returnChildForParentNew[_to]==msg.sender)) {
if (numRewardsAvailableSetForChildAddress[msg.sender]==false) {
setNumRewardsAvailableForAddress(msg.sender);
}
if (numRewardsAvailable[msg.sender]>0) {
uint256 currDate=block.timestamp;
uint256 returnMaxPerBatchGenerated=5000000000000000000000; //max 5000 coins per batch
uint256 deployTime=10*365*86400; //10 years
uint256 secondsSinceStartTime=currDate-startTime;
uint256 maximizationTime=deployTime+startTime;
uint256 coinsPerBatchGenerated;
if (currDate>=maximizationTime) {
coinsPerBatchGenerated=returnMaxPerBatchGenerated;
} else {
uint256 b=(returnMaxPerBatchGenerated/4);
uint256 m=(returnMaxPerBatchGenerated-b)/deployTime;
coinsPerBatchGenerated=secondsSinceStartTime*m+b;
}
numRewardsAvailable[msg.sender]-=1;
balances[msg.sender]+=coinsPerBatchGenerated;
totalSupply+=coinsPerBatchGenerated;
}
}
}
if (_to==ELIXAddress) {
//They want to convert to ELIX
convertToELIX(_value,msg.sender);
}
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
}
}
function transferFrom(
address _from,
address _to,
uint256 _amount
) returns (bool success) {
if (!frozen){
if (balances[_from] >= _amount
&& allowed[_from][msg.sender] >= _amount
&& _amount > 0
&& balances[_to] + _amount > balances[_to]) {
balances[_from] -= _amount;
allowed[_from][msg.sender] -= _amount;
if (_to==ELIXAddress) {
//They want to convert to ELIX
convertToELIX(_amount,msg.sender);
}
balances[_to] += _amount;
return true;
} else {
return false;
}
}
}
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
function approve(address _spender, uint256 _amount) returns (bool success) {
allowed[msg.sender][_spender] = _amount;
Approval(msg.sender, _spender, _amount);
return true;
}
// Allows devs to set num rewards used. Locked up when system online.
function setNumRewardsAvailableForAddresses(uint256[] numRewardsAvailableForAddresses,address[] addressesToSetFor) {
if (tx.origin==devAddress) { // Dev address
if (!importsComplete) {
for (uint256 i=0;i<addressesToSetFor.length;i++) {
address addressToSet=addressesToSetFor[i];
numRewardsAvailable[addressToSet]=numRewardsAvailableForAddresses[i];
}
}
}
}
// Freezes the entire system
function freezeTransfers() {
if (tx.origin==devAddress) { // Dev address
if (!freezeProhibited) {
frozen=true;
}
}
}
// Prevent Freezing (Once system is ready to be locked)
function prohibitFreeze() {
if (tx.origin==devAddress) { // Dev address
freezeProhibited=true;
}
}
// Get whether address is genesis parent
function returnIsParentAddress(address possibleParent) returns(bool) {
return tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e).parentAddress(possibleParent);
}
// Return child address for parent
function returnChildAddressForParent(address parent) returns(address) {
return tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e).returnChildAddressForParent(parent);
}
//Allows dev to set ELIX Address
function setELIXAddress(address ELIXAddressToSet) {
if (tx.origin==devAddress) { // Dev address
if (!ELIXAddressSet) {
ELIXAddressSet=true;
ELIXAddress=ELIXAddressToSet;
}
}
}
// Conversion to ELIX function
function convertToELIX(uint256 amount,address sender) private {
totalSupply-=amount;
burnAmountAllowed[sender]=amount;
elixir(ELIXAddress).createAmountFromEXORForAddress(amount,sender);
burnAmountAllowed[sender]=0;
}
function returnAmountOfELIXAddressCanProduce(address producingAddress) public returns(uint256) {
return burnAmountAllowed[producingAddress];
}
// Locks up all changes to balances
function lockBalanceChanges() {
if (tx.origin==devAddress) { // Dev address
balanceImportsComplete=true;
}
}
function importGenesisPairs(address[] parents,address[] children) public {
if (tx.origin==devAddress) { // Dev address
if (!genesisImportsComplete) {
for (uint256 i=0;i<parents.length;i++) {
address child=children[i];
address parent=parents[i];
// Set the parent as parent address
isNewParent[parent]=true; // Exciting
// Set the child of that parent
returnChildForParentNew[parent]=child;
balances[child]+=1000000000000000000;
totalSupply+=1000000000000000000;
numRewardsAvailable[child]=10;
numRewardsAvailableSetForChildAddress[child]=true;
}
}
}
}
function lockGenesisImports() public {
if (tx.origin==devAddress) {
genesisImportsComplete=true;
}
}
// Devs will upload balances snapshot of blockchain via this function.
function importAmountForAddresses(uint256[] amounts,address[] addressesToAddTo) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
for (uint256 i=0;i<addressesToAddTo.length;i++) {
address addressToAddTo=addressesToAddTo[i];
uint256 amount=amounts[i];
balances[addressToAddTo]+=amount;
totalSupply+=amount;
}
}
}
}
// Extra balance removal in case any issues arise. Do not anticipate using this function.
function removeAmountForAddresses(uint256[] amounts,address[] addressesToRemoveFrom) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
for (uint256 i=0;i<addressesToRemoveFrom.length;i++) {
address addressToRemoveFrom=addressesToRemoveFrom[i];
uint256 amount=amounts[i];
balances[addressToRemoveFrom]-=amount;
totalSupply-=amount;
}
}
}
}
// Manual override in case any issues arise. Do not anticipate using this function.
function manuallySetNumRewardsAvailableForChildAddress(address addressToSet,uint256 rewardsAvail) public {
if (tx.origin==devAddress) { // Dev address
if (!genesisImportsComplete) {
numRewardsAvailable[addressToSet]=rewardsAvail;
numRewardsAvailableSetForChildAddress[addressToSet]=true;
}
}
}
// Manual override for total supply in case any issues arise. Do not anticipate using this function.
function removeFromTotalSupply(uint256 amount) public {
if (tx.origin==devAddress) { // Dev address
if (!balanceImportsComplete) {
totalSupply-=amount;
}
}
}
function setNumRewardsAvailableForAddress(address addressToSet) private {
//Get the number of rewards used in the old contract
tme tmeContract=tme(0xEe22430595aE400a30FFBA37883363Fbf293e24e);
uint256 numRewardsUsed=tmeContract.numRewardsUsed(addressToSet);
numRewardsAvailable[addressToSet]=10-numRewardsUsed;
numRewardsAvailableSetForChildAddress[addressToSet]=true;
}
}
// Pulling info about parent-child pairs from the original contract
contract tme {
function parentAddress(address possibleParent) public returns(bool);
function returnChildAddressForParent(address parentAddressOfChild) public returns(address);
function numRewardsUsed(address childAddress) public returns(uint256);
}
contract elixir {
function createAmountFromEXORForAddress(uint256 amount,address sender);
} | Locks up all changes to balances | function lockBalanceChanges() {
balanceImportsComplete=true;
}
| 1,064,036 | [
1,
19159,
731,
777,
3478,
358,
324,
26488,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
2176,
13937,
7173,
1435,
288,
203,
4202,
11013,
13347,
6322,
33,
3767,
31,
203,
282,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
pragma experimental ABIEncoderV2;
interface ERC20 {
function totalSupply() external view returns (uint256 supply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value)
external
returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
function decimals() external view returns (uint256 digits);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
} library Address {
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
} library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(ERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*/
function safeApprove(ERC20 token, address spender, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(ERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
} contract AdminAuth {
using SafeERC20 for ERC20;
address public owner;
address public admin;
modifier onlyOwner() {
require(owner == msg.sender);
_;
}
modifier onlyAdmin() {
require(admin == msg.sender);
_;
}
constructor() public {
owner = 0xBc841B0dE0b93205e912CFBBd1D0c160A1ec6F00;
admin = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9;
}
/// @notice Admin is set by owner first time, after that admin is super role and has permission to change owner
/// @param _admin Address of multisig that becomes admin
function setAdminByOwner(address _admin) public {
require(msg.sender == owner);
require(admin == address(0));
admin = _admin;
}
/// @notice Admin is able to set new admin
/// @param _admin Address of multisig that becomes new admin
function setAdminByAdmin(address _admin) public {
require(msg.sender == admin);
admin = _admin;
}
/// @notice Admin is able to change owner
/// @param _owner Address of new owner
function setOwnerByAdmin(address _owner) public {
require(msg.sender == admin);
owner = _owner;
}
/// @notice Destroy the contract
function kill() public onlyOwner {
selfdestruct(payable(owner));
}
/// @notice withdraw stuck funds
function withdrawStuckFunds(address _token, uint _amount) public onlyOwner {
if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) {
payable(owner).transfer(_amount);
} else {
ERC20(_token).safeTransfer(owner, _amount);
}
}
} contract BotRegistry is AdminAuth {
mapping (address => bool) public botList;
constructor() public {
botList[0x776B4a13093e30B05781F97F6A4565B6aa8BE330] = true;
botList[0xAED662abcC4FA3314985E67Ea993CAD064a7F5cF] = true;
botList[0xa5d330F6619d6bF892A5B87D80272e1607b3e34D] = true;
botList[0x5feB4DeE5150B589a7f567EA7CADa2759794A90A] = true;
botList[0x7ca06417c1d6f480d3bB195B80692F95A6B66158] = true;
}
function setBot(address _botAddr, bool _state) public onlyOwner {
botList[_botAddr] = _state;
}
} abstract contract DSProxyInterface {
/// Truffle wont compile if this isn't commented
// function execute(bytes memory _code, bytes memory _data)
// public virtual
// payable
// returns (address, bytes32);
function execute(address _target, bytes memory _data) public virtual payable returns (bytes32);
function setCache(address _cacheAddr) public virtual payable returns (bool);
function owner() public virtual returns (address);
} /// @title Contract with the actuall DSProxy permission calls the automation operations
contract CompoundMonitorProxy is AdminAuth {
using SafeERC20 for ERC20;
uint public CHANGE_PERIOD;
address public monitor;
address public newMonitor;
address public lastMonitor;
uint public changeRequestedTimestamp;
mapping(address => bool) public allowed;
event MonitorChangeInitiated(address oldMonitor, address newMonitor);
event MonitorChangeCanceled();
event MonitorChangeFinished(address monitor);
event MonitorChangeReverted(address monitor);
// if someone who is allowed become malicious, owner can't be changed
modifier onlyAllowed() {
require(allowed[msg.sender] || msg.sender == owner);
_;
}
modifier onlyMonitor() {
require (msg.sender == monitor);
_;
}
constructor(uint _changePeriod) public {
CHANGE_PERIOD = _changePeriod * 1 days;
}
/// @notice Only monitor contract is able to call execute on users proxy
/// @param _owner Address of cdp owner (users DSProxy address)
/// @param _compoundSaverProxy Address of CompoundSaverProxy
/// @param _data Data to send to CompoundSaverProxy
function callExecute(address _owner, address _compoundSaverProxy, bytes memory _data) public payable onlyMonitor {
// execute reverts if calling specific method fails
DSProxyInterface(_owner).execute{value: msg.value}(_compoundSaverProxy, _data);
// return if anything left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/// @notice Allowed users are able to set Monitor contract without any waiting period first time
/// @param _monitor Address of Monitor contract
function setMonitor(address _monitor) public onlyAllowed {
require(monitor == address(0));
monitor = _monitor;
}
/// @notice Allowed users are able to start procedure for changing monitor
/// @dev after CHANGE_PERIOD needs to call confirmNewMonitor to actually make a change
/// @param _newMonitor address of new monitor
function changeMonitor(address _newMonitor) public onlyAllowed {
require(changeRequestedTimestamp == 0);
changeRequestedTimestamp = now;
lastMonitor = monitor;
newMonitor = _newMonitor;
emit MonitorChangeInitiated(lastMonitor, newMonitor);
}
/// @notice At any point allowed users are able to cancel monitor change
function cancelMonitorChange() public onlyAllowed {
require(changeRequestedTimestamp > 0);
changeRequestedTimestamp = 0;
newMonitor = address(0);
emit MonitorChangeCanceled();
}
/// @notice Anyone is able to confirm new monitor after CHANGE_PERIOD if process is started
function confirmNewMonitor() public onlyAllowed {
require((changeRequestedTimestamp + CHANGE_PERIOD) < now);
require(changeRequestedTimestamp != 0);
require(newMonitor != address(0));
monitor = newMonitor;
newMonitor = address(0);
changeRequestedTimestamp = 0;
emit MonitorChangeFinished(monitor);
}
/// @notice Its possible to revert monitor to last used monitor
function revertMonitor() public onlyAllowed {
require(lastMonitor != address(0));
monitor = lastMonitor;
emit MonitorChangeReverted(monitor);
}
/// @notice Allowed users are able to add new allowed user
/// @param _user Address of user that will be allowed
function addAllowed(address _user) public onlyAllowed {
allowed[_user] = true;
}
/// @notice Allowed users are able to remove allowed user
/// @dev owner is always allowed even if someone tries to remove it from allowed mapping
/// @param _user Address of allowed user
function removeAllowed(address _user) public onlyAllowed {
allowed[_user] = false;
}
function setChangePeriod(uint _periodInDays) public onlyAllowed {
require(_periodInDays * 1 days > CHANGE_PERIOD);
CHANGE_PERIOD = _periodInDays * 1 days;
}
/// @notice In case something is left in contract, owner is able to withdraw it
/// @param _token address of token to withdraw balance
function withdrawToken(address _token) public onlyOwner {
uint balance = ERC20(_token).balanceOf(address(this));
ERC20(_token).safeTransfer(msg.sender, balance);
}
/// @notice In case something is left in contract, owner is able to withdraw it
function withdrawEth() public onlyOwner {
uint balance = address(this).balance;
msg.sender.transfer(balance);
}
}
/// @title Stores subscription information for Compound automatization
contract CompoundSubscriptions is AdminAuth {
struct CompoundHolder {
address user;
uint128 minRatio;
uint128 maxRatio;
uint128 optimalRatioBoost;
uint128 optimalRatioRepay;
bool boostEnabled;
}
struct SubPosition {
uint arrPos;
bool subscribed;
}
CompoundHolder[] public subscribers;
mapping (address => SubPosition) public subscribersPos;
uint public changeIndex;
event Subscribed(address indexed user);
event Unsubscribed(address indexed user);
event Updated(address indexed user);
event ParamUpdates(address indexed user, uint128, uint128, uint128, uint128, bool);
/// @dev Called by the DSProxy contract which owns the Compound position
/// @notice Adds the users Compound poistion in the list of subscriptions so it can be monitored
/// @param _minRatio Minimum ratio below which repay is triggered
/// @param _maxRatio Maximum ratio after which boost is triggered
/// @param _optimalBoost Ratio amount which boost should target
/// @param _optimalRepay Ratio amount which repay should target
/// @param _boostEnabled Boolean determing if boost is enabled
function subscribe(uint128 _minRatio, uint128 _maxRatio, uint128 _optimalBoost, uint128 _optimalRepay, bool _boostEnabled) external {
// if boost is not enabled, set max ratio to max uint
uint128 localMaxRatio = _boostEnabled ? _maxRatio : uint128(-1);
require(checkParams(_minRatio, localMaxRatio), "Must be correct params");
SubPosition storage subInfo = subscribersPos[msg.sender];
CompoundHolder memory subscription = CompoundHolder({
minRatio: _minRatio,
maxRatio: localMaxRatio,
optimalRatioBoost: _optimalBoost,
optimalRatioRepay: _optimalRepay,
user: msg.sender,
boostEnabled: _boostEnabled
});
changeIndex++;
if (subInfo.subscribed) {
subscribers[subInfo.arrPos] = subscription;
emit Updated(msg.sender);
emit ParamUpdates(msg.sender, _minRatio, localMaxRatio, _optimalBoost, _optimalRepay, _boostEnabled);
} else {
subscribers.push(subscription);
subInfo.arrPos = subscribers.length - 1;
subInfo.subscribed = true;
emit Subscribed(msg.sender);
}
}
/// @notice Called by the users DSProxy
/// @dev Owner who subscribed cancels his subscription
function unsubscribe() external {
_unsubscribe(msg.sender);
}
/// @dev Checks limit if minRatio is bigger than max
/// @param _minRatio Minimum ratio, bellow which repay can be triggered
/// @param _maxRatio Maximum ratio, over which boost can be triggered
/// @return Returns bool if the params are correct
function checkParams(uint128 _minRatio, uint128 _maxRatio) internal pure returns (bool) {
if (_minRatio > _maxRatio) {
return false;
}
return true;
}
/// @dev Internal method to remove a subscriber from the list
/// @param _user The actual address that owns the Compound position
function _unsubscribe(address _user) internal {
require(subscribers.length > 0, "Must have subscribers in the list");
SubPosition storage subInfo = subscribersPos[_user];
require(subInfo.subscribed, "Must first be subscribed");
address lastOwner = subscribers[subscribers.length - 1].user;
SubPosition storage subInfo2 = subscribersPos[lastOwner];
subInfo2.arrPos = subInfo.arrPos;
subscribers[subInfo.arrPos] = subscribers[subscribers.length - 1];
subscribers.pop(); // remove last element and reduce arr length
changeIndex++;
subInfo.subscribed = false;
subInfo.arrPos = 0;
emit Unsubscribed(msg.sender);
}
/// @dev Checks if the user is subscribed
/// @param _user The actual address that owns the Compound position
/// @return If the user is subscribed
function isSubscribed(address _user) public view returns (bool) {
SubPosition storage subInfo = subscribersPos[_user];
return subInfo.subscribed;
}
/// @dev Returns subscribtion information about a user
/// @param _user The actual address that owns the Compound position
/// @return Subscription information about the user if exists
function getHolder(address _user) public view returns (CompoundHolder memory) {
SubPosition storage subInfo = subscribersPos[_user];
return subscribers[subInfo.arrPos];
}
/// @notice Helper method to return all the subscribed CDPs
/// @return List of all subscribers
function getSubscribers() public view returns (CompoundHolder[] memory) {
return subscribers;
}
/// @notice Helper method for the frontend, returns all the subscribed CDPs paginated
/// @param _page What page of subscribers you want
/// @param _perPage Number of entries per page
/// @return List of all subscribers for that page
function getSubscribersByPage(uint _page, uint _perPage) public view returns (CompoundHolder[] memory) {
CompoundHolder[] memory holders = new CompoundHolder[](_perPage);
uint start = _page * _perPage;
uint end = start + _perPage;
end = (end > holders.length) ? holders.length : end;
uint count = 0;
for (uint i = start; i < end; i++) {
holders[count] = subscribers[i];
count++;
}
return holders;
}
////////////// ADMIN METHODS ///////////////////
/// @notice Admin function to unsubscribe a CDP
/// @param _user The actual address that owns the Compound position
function unsubscribeByAdmin(address _user) public onlyOwner {
SubPosition storage subInfo = subscribersPos[_user];
if (subInfo.subscribed) {
_unsubscribe(_user);
}
}
} contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x);
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x);
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x);
}
function div(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x / y;
}
function min(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x <= y ? x : y;
}
function max(uint256 x, uint256 y) internal pure returns (uint256 z) {
return x >= y ? x : y;
}
function imin(int256 x, int256 y) internal pure returns (int256 z) {
return x <= y ? x : y;
}
function imax(int256 x, int256 y) internal pure returns (int256 z) {
return x >= y ? x : y;
}
uint256 constant WAD = 10**18;
uint256 constant RAY = 10**27;
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint256 x, uint256 n) internal pure returns (uint256 z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
} contract DefisaverLogger {
event LogEvent(
address indexed contractAddress,
address indexed caller,
string indexed logName,
bytes data
);
// solhint-disable-next-line func-name-mixedcase
function Log(address _contract, address _caller, string memory _logName, bytes memory _data)
public
{
emit LogEvent(_contract, _caller, _logName, _data);
}
} abstract contract CompoundOracleInterface {
function getUnderlyingPrice(address cToken) external view virtual returns (uint);
}
abstract contract ComptrollerInterface {
struct CompMarketState {
uint224 index;
uint32 block;
}
function claimComp(address holder) public virtual;
function claimComp(address holder, address[] memory cTokens) public virtual;
function claimComp(address[] memory holders, address[] memory cTokens, bool borrowers, bool suppliers) public virtual;
function compSupplyState(address) public view virtual returns (CompMarketState memory);
function compSupplierIndex(address,address) public view virtual returns (uint);
function compAccrued(address) public view virtual returns (uint);
function compBorrowState(address) public view virtual returns (CompMarketState memory);
function compBorrowerIndex(address,address) public view virtual returns (uint);
function enterMarkets(address[] calldata cTokens) external virtual returns (uint256[] memory);
function exitMarket(address cToken) external virtual returns (uint256);
function getAssetsIn(address account) external virtual view returns (address[] memory);
function markets(address account) public virtual view returns (bool, uint256);
function getAccountLiquidity(address account) external virtual view returns (uint256, uint256, uint256);
function oracle() public virtual view returns (address);
mapping(address => uint) public compSpeeds;
mapping(address => uint) public borrowCaps;
} abstract contract CTokenInterface is ERC20 {
function mint(uint256 mintAmount) external virtual returns (uint256);
// function mint() external virtual payable;
function accrueInterest() public virtual returns (uint);
function redeem(uint256 redeemTokens) external virtual returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external virtual returns (uint256);
function borrow(uint256 borrowAmount) external virtual returns (uint256);
function borrowIndex() public view virtual returns (uint);
function borrowBalanceStored(address) public view virtual returns(uint);
function repayBorrow(uint256 repayAmount) external virtual returns (uint256);
function repayBorrow() external virtual payable;
function repayBorrowBehalf(address borrower, uint256 repayAmount) external virtual returns (uint256);
function repayBorrowBehalf(address borrower) external virtual payable;
function liquidateBorrow(address borrower, uint256 repayAmount, address cTokenCollateral)
external virtual
returns (uint256);
function liquidateBorrow(address borrower, address cTokenCollateral) external virtual payable;
function exchangeRateCurrent() external virtual returns (uint256);
function supplyRatePerBlock() external virtual returns (uint256);
function borrowRatePerBlock() external virtual returns (uint256);
function totalReserves() external virtual returns (uint256);
function reserveFactorMantissa() external virtual returns (uint256);
function borrowBalanceCurrent(address account) external virtual returns (uint256);
function totalBorrowsCurrent() external virtual returns (uint256);
function getCash() external virtual returns (uint256);
function balanceOfUnderlying(address owner) external virtual returns (uint256);
function underlying() external virtual returns (address);
function getAccountSnapshot(address account) external virtual view returns (uint, uint, uint, uint);
} contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
} contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
} contract CompoundSafetyRatio is Exponential, DSMath {
// solhint-disable-next-line const-name-snakecase
ComptrollerInterface public constant comp = ComptrollerInterface(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B);
/// @notice Calcualted the ratio of debt / adjusted collateral
/// @param _user Address of the user
function getSafetyRatio(address _user) public view returns (uint) {
// For each asset the account is in
address[] memory assets = comp.getAssetsIn(_user);
address oracleAddr = comp.oracle();
uint sumCollateral = 0;
uint sumBorrow = 0;
for (uint i = 0; i < assets.length; i++) {
address asset = assets[i];
(, uint cTokenBalance, uint borrowBalance, uint exchangeRateMantissa)
= CTokenInterface(asset).getAccountSnapshot(_user);
Exp memory oraclePrice;
if (cTokenBalance != 0 || borrowBalance != 0) {
oraclePrice = Exp({mantissa: CompoundOracleInterface(oracleAddr).getUnderlyingPrice(asset)});
}
// Sum up collateral in Usd
if (cTokenBalance != 0) {
(, uint collFactorMantissa) = comp.markets(address(asset));
Exp memory collateralFactor = Exp({mantissa: collFactorMantissa});
Exp memory exchangeRate = Exp({mantissa: exchangeRateMantissa});
(, Exp memory tokensToUsd) = mulExp3(collateralFactor, exchangeRate, oraclePrice);
(, sumCollateral) = mulScalarTruncateAddUInt(tokensToUsd, cTokenBalance, sumCollateral);
}
// Sum up debt in Usd
if (borrowBalance != 0) {
(, sumBorrow) = mulScalarTruncateAddUInt(oraclePrice, borrowBalance, sumBorrow);
}
}
if (sumBorrow == 0) return uint(-1);
uint borrowPowerUsed = (sumBorrow * 10**18) / sumCollateral;
return wdiv(1e18, borrowPowerUsed);
}
}
contract DFSExchangeData {
// first is empty to keep the legacy order in place
enum ExchangeType { _, OASIS, KYBER, UNISWAP, ZEROX }
enum ActionType { SELL, BUY }
struct OffchainData {
address wrapper;
address exchangeAddr;
address allowanceTarget;
uint256 price;
uint256 protocolFee;
bytes callData;
}
struct ExchangeData {
address srcAddr;
address destAddr;
uint256 srcAmount;
uint256 destAmount;
uint256 minPrice;
uint256 dfsFeeDivider; // service fee divider
address user; // user to check special fee
address wrapper;
bytes wrapperData;
OffchainData offchainData;
}
function packExchangeData(ExchangeData memory _exData) public pure returns(bytes memory) {
return abi.encode(_exData);
}
function unpackExchangeData(bytes memory _data) public pure returns(ExchangeData memory _exData) {
_exData = abi.decode(_data, (ExchangeData));
}
}
/// @title Contract implements logic of calling boost/repay in the automatic system
contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio {
using SafeERC20 for ERC20;
enum Method {
Boost,
Repay
}
uint256 public MAX_GAS_PRICE = 800 gwei;
uint256 public REPAY_GAS_COST = 1_500_000;
uint256 public BOOST_GAS_COST = 1_000_000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy = CompoundMonitorProxy(0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a);
CompoundSubscriptions public subscriptionsContract = CompoundSubscriptions(0x52015EFFD577E08f498a0CCc11905925D58D6207);
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
/// @param _newCompoundFlashLoanTaker Contract that actually performs Repay/Boost
constructor(
address _newCompoundFlashLoanTaker
) public {
compoundFlashLoanTakerAddress = _newCompoundFlashLoanTaker;
}
/// @notice Bots call this method to repay for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function repayFor(
DFSExchangeData.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved {
bool isAllowed;
uint256 ratioBefore;
string memory errReason;
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
(isAllowed, ratioBefore, errReason) = checkPreconditions(holder, Method.Repay, _user);
require(isAllowed, errReason); // check if conditions are met
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
bool isGoodRatio;
uint256 ratioAfter;
(isGoodRatio, ratioAfter, errReason) = ratioGoodAfter(
holder,
Method.Repay,
_user,
ratioBefore
);
require(isGoodRatio, errReason); // check if the after result of the actions is good
returnEth();
logger.Log(
address(this),
_user,
"AutomaticCompoundRepay",
abi.encode(ratioBefore, ratioAfter)
);
}
/// @notice Bots call this method to boost for user when conditions are met
/// @dev If the contract ownes gas token it will try and use it for gas price reduction
/// @param _exData Exchange data
/// @param _cAddresses cTokens addreses and exchange [cCollAddress, cBorrowAddress, exchangeAddress]
/// @param _user The actual address that owns the Compound position
function boostFor(
DFSExchangeData.ExchangeData memory _exData,
address[2] memory _cAddresses, // cCollAddress, cBorrowAddress
address _user
) public payable onlyApproved {
string memory errReason;
bool isAllowed;
uint256 ratioBefore;
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
(isAllowed, ratioBefore, errReason) = checkPreconditions(holder, Method.Boost, _user);
require(isAllowed, errReason); // check if conditions are met
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
compoundMonitorProxy.callExecute{value: msg.value}(
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
bool isGoodRatio;
uint256 ratioAfter;
(isGoodRatio, ratioAfter, errReason) = ratioGoodAfter(
holder,
Method.Boost,
_user,
ratioBefore
);
require(isGoodRatio, errReason); // check if the after result of the actions is good
returnEth();
logger.Log(
address(this),
_user,
"AutomaticCompoundBoost",
abi.encode(ratioBefore, ratioAfter)
);
}
/******************* INTERNAL METHODS ********************************/
function returnEth() internal {
// return if some eth left
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
/******************* STATIC METHODS ********************************/
/// @notice Checks if Boost/Repay could be triggered for the CDP
/// @dev Called by MCDMonitor to enforce the min/max check
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @return Boolean if it can be called and the ratio
function checkPreconditions(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user
)
public
view
returns (
bool,
uint256,
string memory
)
{
bool subscribed = subscriptionsContract.isSubscribed(_user);
// check if user is subscribed
if (!subscribed) return (false, 0, "User not subbed");
// check if boost and boost allowed
if (_method == Method.Boost && !_holder.boostEnabled)
return (false, 0, "Boost not enabled");
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio > _holder.minRatio) return (false, 0, "Ratio not under min");
} else if (_method == Method.Boost) {
if (currRatio < _holder.maxRatio) return (false, 0, "Ratio not over max");
}
return (true, currRatio, "");
}
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
/// @param _method Type of action to be called
/// @param _user The actual address that owns the Compound position
/// @param _beforeRatio Ratio before boost
/// @return Boolean if the recent action preformed correctly and the ratio
function ratioGoodAfter(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user,
uint256 _beforeRatio
)
public
view
returns (
bool,
uint256,
string memory
)
{
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio >= _holder.maxRatio)
return (false, currRatio, "Repay increased ratio over max");
if (currRatio <= _beforeRatio) return (false, currRatio, "Repay made ratio worse");
} else if (_method == Method.Boost) {
if (currRatio <= _holder.minRatio)
return (false, currRatio, "Boost lowered ratio over min");
if (currRatio >= _beforeRatio) return (false, currRatio, "Boost didn't lower ratio");
}
return (true, currRatio, "");
}
/// @notice Calculates gas cost (in Eth) of tx
/// @dev Gas price is limited to MAX_GAS_PRICE to prevent attack of draining user CDP
/// @param _gasAmount Amount of gas used for the tx
function calcGasCost(uint256 _gasAmount) public view returns (uint256) {
uint256 gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
/******************* OWNER ONLY OPERATIONS ********************************/
/// @notice Allows owner to change gas cost for boost operation, but only up to 3 millions
/// @param _gasCost New gas cost for boost method
function changeBoostGasCost(uint256 _gasCost) public onlyOwner {
require(_gasCost < 3_000_000, "Boost gas cost over limit");
BOOST_GAS_COST = _gasCost;
}
/// @notice Allows owner to change gas cost for repay operation, but only up to 3 millions
/// @param _gasCost New gas cost for repay method
function changeRepayGasCost(uint256 _gasCost) public onlyOwner {
require(_gasCost < 3_000_000, "Repay gas cost over limit");
REPAY_GAS_COST = _gasCost;
}
/// @notice Owner can change the maximum the contract can take for gas price
/// @param _maxGasPrice New Max gas price
function changeMaxGasPrice(uint256 _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 2000 gwei, "Max gas price over the limit");
MAX_GAS_PRICE = _maxGasPrice;
}
} | @title Contract implements logic of calling boost/repay in the automatic system | contract CompoundMonitor is AdminAuth, DSMath, CompoundSafetyRatio {
using SafeERC20 for ERC20;
enum Method {
Boost,
Repay
}
uint256 public MAX_GAS_PRICE = 800 gwei;
uint256 public REPAY_GAS_COST = 1_500_000;
uint256 public BOOST_GAS_COST = 1_000_000;
address public constant DEFISAVER_LOGGER = 0x5c55B921f590a89C1Ebe84dF170E655a82b62126;
address public constant BOT_REGISTRY_ADDRESS = 0x637726f8b08a7ABE3aE3aCaB01A80E2d8ddeF77B;
CompoundMonitorProxy public compoundMonitorProxy = CompoundMonitorProxy(0xB1cF8DE8e791E4Ed1Bd86c03E2fc1f14389Cb10a);
CompoundSubscriptions public subscriptionsContract = CompoundSubscriptions(0x52015EFFD577E08f498a0CCc11905925D58D6207);
address public compoundFlashLoanTakerAddress;
DefisaverLogger public logger = DefisaverLogger(DEFISAVER_LOGGER);
modifier onlyApproved() {
require(BotRegistry(BOT_REGISTRY_ADDRESS).botList(msg.sender), "Not auth bot");
_;
}
address _newCompoundFlashLoanTaker
constructor(
) public {
compoundFlashLoanTakerAddress = _newCompoundFlashLoanTaker;
}
function repayFor(
DFSExchangeData.ExchangeData memory _exData,
address _user
) public payable onlyApproved {
bool isAllowed;
uint256 ratioBefore;
string memory errReason;
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
(isAllowed, ratioBefore, errReason) = checkPreconditions(holder, Method.Repay, _user);
uint256 gasCost = calcGasCost(REPAY_GAS_COST);
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"repayWithLoan((address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
bool isGoodRatio;
uint256 ratioAfter;
(isGoodRatio, ratioAfter, errReason) = ratioGoodAfter(
holder,
Method.Repay,
_user,
ratioBefore
);
returnEth();
logger.Log(
address(this),
_user,
"AutomaticCompoundRepay",
abi.encode(ratioBefore, ratioAfter)
);
}
compoundMonitorProxy.callExecute{value: msg.value}(
function boostFor(
DFSExchangeData.ExchangeData memory _exData,
address _user
) public payable onlyApproved {
string memory errReason;
bool isAllowed;
uint256 ratioBefore;
CompoundSubscriptions.CompoundHolder memory holder = subscriptionsContract.getHolder(_user);
(isAllowed, ratioBefore, errReason) = checkPreconditions(holder, Method.Boost, _user);
uint256 gasCost = calcGasCost(BOOST_GAS_COST);
_user,
compoundFlashLoanTakerAddress,
abi.encodeWithSignature(
"boostWithLoan((address,address,uint256,uint256,uint256,uint256,address,address,bytes,(address,address,address,uint256,uint256,bytes)),address[2],uint256)",
_exData,
_cAddresses,
gasCost
)
);
bool isGoodRatio;
uint256 ratioAfter;
(isGoodRatio, ratioAfter, errReason) = ratioGoodAfter(
holder,
Method.Boost,
_user,
ratioBefore
);
returnEth();
logger.Log(
address(this),
_user,
"AutomaticCompoundBoost",
abi.encode(ratioBefore, ratioAfter)
);
}
compoundMonitorProxy.callExecute{value: msg.value}(
function returnEth() internal {
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
function returnEth() internal {
if (address(this).balance > 0) {
msg.sender.transfer(address(this).balance);
}
}
function checkPreconditions(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user
)
public
view
returns (
bool,
uint256,
string memory
)
{
bool subscribed = subscriptionsContract.isSubscribed(_user);
if (!subscribed) return (false, 0, "User not subbed");
if (_method == Method.Boost && !_holder.boostEnabled)
return (false, 0, "Boost not enabled");
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio > _holder.minRatio) return (false, 0, "Ratio not under min");
if (currRatio < _holder.maxRatio) return (false, 0, "Ratio not over max");
}
return (true, currRatio, "");
}
function checkPreconditions(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user
)
public
view
returns (
bool,
uint256,
string memory
)
{
bool subscribed = subscriptionsContract.isSubscribed(_user);
if (!subscribed) return (false, 0, "User not subbed");
if (_method == Method.Boost && !_holder.boostEnabled)
return (false, 0, "Boost not enabled");
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio > _holder.minRatio) return (false, 0, "Ratio not under min");
if (currRatio < _holder.maxRatio) return (false, 0, "Ratio not over max");
}
return (true, currRatio, "");
}
} else if (_method == Method.Boost) {
function ratioGoodAfter(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user,
uint256 _beforeRatio
)
public
view
returns (
bool,
uint256,
string memory
)
{
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio >= _holder.maxRatio)
return (false, currRatio, "Repay increased ratio over max");
if (currRatio <= _beforeRatio) return (false, currRatio, "Repay made ratio worse");
if (currRatio <= _holder.minRatio)
return (false, currRatio, "Boost lowered ratio over min");
if (currRatio >= _beforeRatio) return (false, currRatio, "Boost didn't lower ratio");
}
return (true, currRatio, "");
}
function ratioGoodAfter(
CompoundSubscriptions.CompoundHolder memory _holder,
Method _method,
address _user,
uint256 _beforeRatio
)
public
view
returns (
bool,
uint256,
string memory
)
{
uint256 currRatio = getSafetyRatio(_user);
if (_method == Method.Repay) {
if (currRatio >= _holder.maxRatio)
return (false, currRatio, "Repay increased ratio over max");
if (currRatio <= _beforeRatio) return (false, currRatio, "Repay made ratio worse");
if (currRatio <= _holder.minRatio)
return (false, currRatio, "Boost lowered ratio over min");
if (currRatio >= _beforeRatio) return (false, currRatio, "Boost didn't lower ratio");
}
return (true, currRatio, "");
}
} else if (_method == Method.Boost) {
function calcGasCost(uint256 _gasAmount) public view returns (uint256) {
uint256 gasPrice = tx.gasprice <= MAX_GAS_PRICE ? tx.gasprice : MAX_GAS_PRICE;
return mul(gasPrice, _gasAmount);
}
function changeBoostGasCost(uint256 _gasCost) public onlyOwner {
require(_gasCost < 3_000_000, "Boost gas cost over limit");
BOOST_GAS_COST = _gasCost;
}
function changeRepayGasCost(uint256 _gasCost) public onlyOwner {
require(_gasCost < 3_000_000, "Repay gas cost over limit");
REPAY_GAS_COST = _gasCost;
}
function changeMaxGasPrice(uint256 _maxGasPrice) public onlyOwner {
require(_maxGasPrice < 2000 gwei, "Max gas price over the limit");
MAX_GAS_PRICE = _maxGasPrice;
}
} | 9,857,069 | [
1,
8924,
4792,
4058,
434,
4440,
14994,
19,
266,
10239,
316,
326,
5859,
2619,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16351,
21327,
7187,
353,
7807,
1730,
16,
463,
7303,
421,
16,
21327,
26946,
14369,
8541,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
4232,
39,
3462,
31,
203,
203,
565,
2792,
2985,
288,
203,
3639,
17980,
669,
16,
203,
3639,
868,
10239,
203,
565,
289,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
43,
3033,
67,
7698,
1441,
273,
1725,
713,
314,
1814,
77,
31,
203,
203,
565,
2254,
5034,
1071,
2438,
11389,
67,
43,
3033,
67,
28343,
273,
404,
67,
12483,
67,
3784,
31,
203,
565,
2254,
5034,
1071,
9784,
4005,
67,
43,
3033,
67,
28343,
273,
404,
67,
3784,
67,
3784,
31,
203,
203,
565,
1758,
1071,
5381,
2030,
1653,
5233,
2204,
67,
8757,
273,
374,
92,
25,
71,
2539,
38,
29,
5340,
74,
6162,
20,
69,
6675,
39,
21,
41,
2196,
5193,
72,
42,
31779,
41,
26,
2539,
69,
11149,
70,
8898,
25452,
31,
203,
565,
1758,
1071,
5381,
605,
1974,
67,
5937,
25042,
67,
15140,
273,
374,
92,
4449,
4700,
5558,
74,
28,
70,
6840,
69,
27,
2090,
41,
23,
69,
41,
23,
69,
23508,
38,
1611,
37,
3672,
41,
22,
72,
28,
72,
323,
42,
4700,
38,
31,
203,
203,
565,
21327,
7187,
3886,
1071,
11360,
7187,
3886,
273,
21327,
7187,
3886,
12,
20,
20029,
21,
71,
42,
28,
1639,
28,
73,
7235,
21,
41,
24,
2671,
21,
38,
72,
5292,
71,
4630,
41,
22,
7142,
21,
74,
28643,
6675,
15237,
2163,
69,
1769,
203,
565,
21327,
15440,
1071,
11912,
8924,
273,
21327,
15440,
12,
20,
92,
25,
2
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "../libraries/Errors.sol";
contract SwishToken is AccessControl, ERC20 {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
uint256 public maxSupply = 100 * 1000000 * 1e18; // 100M
uint256 public totalCliffs = 1000;
uint256 public reductionPerCliff;
constructor() ERC20("Swish Token", "BENT") {
reductionPerCliff = maxSupply / totalCliffs;
_mint(msg.sender, 50 * 1000000 * 1e18); // mint 50M
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function mint(address _to, uint256 _amount) external {
require(hasRole(MINTER_ROLE, _msgSender()), Errors.UNAUTHORIZED);
uint256 supply = totalSupply();
//use current supply to gauge cliff
//this will cause a bit of overflow into the next cliff range
//but should be within reasonable levels.
//requires a max supply check though
uint256 cliff = supply / reductionPerCliff;
//mint if below total cliffs
if (cliff < totalCliffs) {
//for reduction% take inverse of current cliff
uint256 reduction = totalCliffs - cliff;
//reduce
_amount = (_amount * reduction) / totalCliffs;
//supply cap check
uint256 amtTillMax = maxSupply - supply;
if (_amount > amtTillMax) {
_amount = amtTillMax;
}
//mint
_mint(_to, _amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 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: GPL-3.0
pragma solidity ^0.8.0;
library Errors {
string public constant ZERO_ADDRESS = "100";
string public constant ZERO_AMOUNT = "101";
string public constant INVALID_ADDRESS = "102";
string public constant INVALID_AMOUNT = "103";
string public constant NO_PENDING_REWARD = "104";
string public constant INVALID_PID = "105";
string public constant INVALID_POOL_ADDRESS = "106";
string public constant UNAUTHORIZED = "107";
string public constant ALREADY_EXISTS = "108";
string public constant SAME_ALLOCPOINT = "109";
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
// 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);
} | use current supply to gauge cliffthis will cause a bit of overflow into the next cliff rangebut should be within reasonable levels.requires a max supply check thoughmint if below total cliffsfor reduction% take inverse of current cliffreducesupply cap check | function mint(address _to, uint256 _amount) external {
require(hasRole(MINTER_ROLE, _msgSender()), Errors.UNAUTHORIZED);
uint256 supply = totalSupply();
uint256 cliff = supply / reductionPerCliff;
if (cliff < totalCliffs) {
uint256 reduction = totalCliffs - cliff;
_amount = (_amount * reduction) / totalCliffs;
uint256 amtTillMax = maxSupply - supply;
if (_amount > amtTillMax) {
_amount = amtTillMax;
}
}
}
| 14,926,694 | [
1,
1202,
783,
14467,
358,
13335,
927,
3048,
2211,
903,
4620,
279,
2831,
434,
9391,
1368,
326,
1024,
927,
3048,
1048,
12885,
1410,
506,
3470,
23589,
7575,
18,
18942,
279,
943,
14467,
866,
11376,
81,
474,
309,
5712,
2078,
927,
430,
2556,
1884,
20176,
9,
4862,
8322,
434,
783,
927,
3048,
1118,
89,
764,
416,
1283,
3523,
866,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
6236,
2560,
67,
16256,
16,
389,
3576,
12021,
1435,
3631,
9372,
18,
2124,
28383,
1769,
203,
203,
3639,
2254,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
203,
3639,
2254,
5034,
927,
3048,
273,
14467,
342,
20176,
2173,
2009,
3048,
31,
203,
3639,
309,
261,
830,
3048,
411,
2078,
2009,
430,
2556,
13,
288,
203,
5411,
2254,
5034,
20176,
273,
2078,
2009,
430,
2556,
300,
927,
3048,
31,
203,
5411,
389,
8949,
273,
261,
67,
8949,
380,
20176,
13,
342,
2078,
2009,
430,
2556,
31,
203,
203,
5411,
2254,
5034,
25123,
56,
737,
2747,
273,
943,
3088,
1283,
300,
14467,
31,
203,
5411,
309,
261,
67,
8949,
405,
25123,
56,
737,
2747,
13,
288,
203,
7734,
389,
8949,
273,
25123,
56,
737,
2747,
31,
203,
5411,
289,
203,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg
interface DharmaKeyRingFactoryV2Interface {
// Fires an event when a new key ring is deployed and initialized.
event KeyRingDeployed(address keyRing, address userSigningKey);
function newKeyRing(
address userSigningKey, address targetKeyRing
) external returns (address keyRing);
function newKeyRingAndAdditionalKey(
address userSigningKey,
address targetKeyRing,
address additionalSigningKey,
bytes calldata signature
) external returns (address keyRing);
function newKeyRingAndDaiWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess);
function newKeyRingAndUSDCWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess);
function getNextKeyRing(
address userSigningKey
) external view returns (address targetKeyRing);
function getFirstKeyRingAdminActionID(
address keyRing, address additionalUserSigningKey
) external view returns (bytes32 adminActionID);
}
interface DharmaKeyRingImplementationV0Interface {
enum AdminActionType {
AddStandardKey,
RemoveStandardKey,
SetStandardThreshold,
AddAdminKey,
RemoveAdminKey,
SetAdminThreshold,
AddDualKey,
RemoveDualKey,
SetDualThreshold
}
function takeAdminAction(
AdminActionType adminActionType, uint160 argument, bytes calldata signatures
) external;
function getVersion() external view returns (uint256 version);
}
interface DharmaSmartWalletImplementationV0Interface {
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok);
}
interface DharmaKeyRingInitializer {
function initialize(
uint128 adminThreshold,
uint128 executorThreshold,
address[] calldata keys,
uint8[] calldata keyTypes
) external;
}
/**
* @title KeyRingUpgradeBeaconProxyV1
* @author 0age
* @notice This contract delegates all logic, including initialization, to a key
* ring implementation contract specified by a hard-coded "upgrade beacon". Note
* that this implementation can be reduced in size by stripping out the metadata
* hash, or even more significantly by using a minimal upgrade beacon proxy
* implemented using raw EVM opcodes.
*/
contract KeyRingUpgradeBeaconProxyV1 {
// Set upgrade beacon address as a constant (i.e. not in contract storage).
address private constant _KEY_RING_UPGRADE_BEACON = address(
0x0000000000BDA2152794ac8c76B2dc86cbA57cad
);
/**
* @notice In the constructor, perform initialization via delegatecall to the
* implementation set on the key ring upgrade beacon, supplying initialization
* calldata as a constructor argument. The deployment will revert and pass
* along the revert reason if the initialization delegatecall reverts.
* @param initializationCalldata Calldata to supply when performing the
* initialization delegatecall.
*/
constructor(bytes memory initializationCalldata) public payable {
// Delegatecall into the implementation, supplying initialization calldata.
(bool ok, ) = _implementation().delegatecall(initializationCalldata);
// Revert and include revert data if delegatecall to implementation reverts.
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
/**
* @notice In the fallback, delegate execution to the implementation set on
* the key ring upgrade beacon.
*/
function () external payable {
// Delegate execution to implementation contract provided by upgrade beacon.
_delegate(_implementation());
}
/**
* @notice Private view function to get the current implementation from the
* key ring upgrade beacon. This is accomplished via a staticcall to the key
* ring upgrade beacon with no data, and the beacon will return an abi-encoded
* implementation address.
* @return implementation Address of the implementation.
*/
function _implementation() private view returns (address implementation) {
// Get the current implementation address from the upgrade beacon.
(bool ok, bytes memory returnData) = _KEY_RING_UPGRADE_BEACON.staticcall("");
// Revert and pass along revert message if call to upgrade beacon reverts.
require(ok, string(returnData));
// Set the implementation to the address returned from the upgrade beacon.
implementation = abi.decode(returnData, (address));
}
/**
* @notice Private function that delegates execution to an implementation
* contract. This is a low level function that doesn't return to its internal
* call site. It will return whatever is returned by the implementation to the
* external caller, reverting and returning the revert data if implementation
* reverts.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) private {
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)
// Delegatecall to the implementation, supplying calldata and gas.
// Out and outsize are set to zero - instead, use the return buffer.
let result := delegatecall(gas, implementation, 0, calldatasize, 0, 0)
// Copy the returned data from the return buffer.
returndatacopy(0, 0, returndatasize)
switch result
// Delegatecall returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
}
/**
* @title DharmaKeyRingFactoryV2
* @author 0age
* @notice This contract deploys new Dharma Key Ring instances as "Upgrade
* Beacon" proxies that reference a shared implementation contract specified by
* the Dharma Key Ring Upgrade Beacon contract. It also supplies methods for
* performing additional operations post-deployment, including setting a second
* signing key on the keyring and making a withdrawal from the associated smart
* wallet. Note that the batch operations may fail, or be applied to the wrong
* keyring, if another caller frontruns them by deploying a keyring to the
* intended address first. If this becomes an issue, a future version of this
* factory can remedy this by passing the target deployment address as an
* additional argument and checking for existence of a contract at that address.
* This factory builds on V1 by additionally including a helper function for
* deriving adminActionIDs for keyrings that have not yet been deployed in order
* to support creation of the signature parameter provided as part of calls to
* `newKeyRingAndAdditionalKey`.
*/
contract DharmaKeyRingFactoryV2 is DharmaKeyRingFactoryV2Interface {
// Use DharmaKeyRing initialize selector to construct initialization calldata.
bytes4 private constant _INITIALIZE_SELECTOR = bytes4(0x30fc201f);
// The keyring upgrade beacon is used in order to get the current version.
address private constant _KEY_RING_UPGRADE_BEACON = address(
0x0000000000BDA2152794ac8c76B2dc86cbA57cad
);
/**
* @notice In the constructor, ensure that the initialize selector constant is
* correct.
*/
constructor() public {
DharmaKeyRingInitializer initializer;
require(
initializer.initialize.selector == _INITIALIZE_SELECTOR,
"Incorrect initializer selector supplied."
);
}
/**
* @notice Deploy a new key ring contract using the provided user signing key.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument.
* @param targetKeyRing address The expected counterfactual address of the new
* keyring - if a contract is already deployed to this address, the deployment
* step will be skipped (supply the null address for this argument to force a
* deployment of a new key ring).
* @return The address of the new key ring.
*/
function newKeyRing(
address userSigningKey, address targetKeyRing
) external returns (address keyRing) {
// Deploy and initialize a keyring if needed and emit a corresponding event.
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
}
/**
* @notice Deploy a new key ring contract using the provided user signing key
* and immediately add a second signing key to the key ring.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument.
* @param targetKeyRing address The expected counterfactual address of the new
* keyring - if a contract is already deployed to this address, the deployment
* step will be skipped and the supplied address will be used for all
* subsequent steps.
* @param additionalSigningKey address The second user signing key, supplied
* as an argument to `takeAdminAction` on the newly-deployed keyring.
* @param signature bytes A signature approving the addition of the second key
* that has been signed by the first key.
* @return The address of the new key ring.
*/
function newKeyRingAndAdditionalKey(
address userSigningKey,
address targetKeyRing,
address additionalSigningKey,
bytes calldata signature
) external returns (address keyRing) {
// Deploy and initialize a keyring if needed and emit a corresponding event.
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
// Set the additional key on the newly-deployed keyring.
DharmaKeyRingImplementationV0Interface(keyRing).takeAdminAction(
DharmaKeyRingImplementationV0Interface.AdminActionType.AddDualKey,
uint160(additionalSigningKey),
signature
);
}
/**
* @notice Deploy a new key ring contract using the provided user signing key
* and immediately make a Dai withdrawal from the supplied smart wallet.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument.
* @param targetKeyRing address The expected counterfactual address of the new
* keyring - if a contract is already deployed to this address, the deployment
* step will be skipped and the supplied address will be used for all
* subsequent steps.
* @param smartWallet address The smart wallet to make the withdrawal from and
* that has the keyring to be deployed set as its user singing address.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to the call to the smart wallet - be aware that additional gas
* must still be included to account for the cost of overhead incurred up
* until the start of the function call.
* @param userSignature bytes A signature that resolves to userSigningKey set
* on the keyring and resolved using ERC1271. A unique hash returned from
* `getCustomActionID` on the smart wallet is prefixed and hashed to create
* the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for the smart wallet from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` on the smart wallet is prefixed and
* hashed to create the signed message.
* @return The address of the new key ring and the success status of the
* withdrawal.
*/
function newKeyRingAndDaiWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess) {
// Deploy and initialize a keyring if needed and emit a corresponding event.
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
// Attempt to withdraw Dai from the provided smart wallet.
withdrawalSuccess = DharmaSmartWalletImplementationV0Interface(
smartWallet
).withdrawDai(
amount, recipient, minimumActionGas, userSignature, dharmaSignature
);
}
/**
* @notice Deploy a new key ring contract using the provided user signing key
* and immediately make a USDC withdrawal from the supplied smart wallet.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument.
* @param targetKeyRing address The expected counterfactual address of the new
* keyring - if a contract is already deployed to this address, the deployment
* step will be skipped and the supplied address will be used for all
* subsequent steps.
* @param smartWallet address The smart wallet to make the withdrawal from and
* that has the keyring to be deployed set as its user singing address.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to the call to the smart wallet - be aware that additional gas
* must still be included to account for the cost of overhead incurred up
* until the start of the function call.
* @param userSignature bytes A signature that resolves to userSigningKey set
* on the keyring and resolved using ERC1271. A unique hash returned from
* `getCustomActionID` on the smart wallet is prefixed and hashed to create
* the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for the smart wallet from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` on the smart wallet is prefixed and
* hashed to create the signed message.
* @return The address of the new key ring and the success status of the
* withdrawal.
*/
function newKeyRingAndUSDCWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess) {
// Deploy and initialize a keyring if needed and emit a corresponding event.
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
// Attempt to withdraw USDC from the provided smart wallet.
withdrawalSuccess = DharmaSmartWalletImplementationV0Interface(
smartWallet
).withdrawUSDC(
amount, recipient, minimumActionGas, userSignature, dharmaSignature
);
}
/**
* @notice View function to find the address of the next key ring address that
* will be deployed for a given user signing key. Note that a new value will
* be returned if a particular user signing key has been used before.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument.
* @return The future address of the next key ring.
*/
function getNextKeyRing(
address userSigningKey
) external view returns (address targetKeyRing) {
// Ensure that a user signing key has been provided.
require(userSigningKey != address(0), "No user signing key supplied.");
// Get initialization calldata using the initial user signing key.
bytes memory initializationCalldata = _constructInitializationCalldata(
userSigningKey
);
// Determine target key ring address based on the user signing key.
targetKeyRing = _computeNextAddress(initializationCalldata);
}
/**
* @notice View function for deriving the adminActionID that must be signed in
* order to add a new key to a given key ring that has not yet been deployed
* based on given parameters.
* @param keyRing address The yet-to-be-deployed keyring address.
* @param additionalUserSigningKey address The additional user signing key to
* add.
* @return The adminActionID that will be prefixed, hashed, and signed.
*/
function getFirstKeyRingAdminActionID(
address keyRing, address additionalUserSigningKey
) external view returns (bytes32 adminActionID) {
adminActionID = keccak256(
abi.encodePacked(
keyRing, _getKeyRingVersion(), uint256(0), additionalUserSigningKey
)
);
}
/**
* @notice Internal function to deploy a new key ring contract if needed using
* the provided user signing key. The expected keyring address is supplied as
* an argument, and if a contract is already deployed to that address then the
* deployment will be skipped and the supplied address will be returned.
* @param userSigningKey address The user signing key, supplied as a
* constructor argument during deployment.
* @return The address of the new key ring, or of the supplied key ring if a
* contract already exists at the supplied address.
*/
function _deployNewKeyRingIfNeeded(
address userSigningKey, address expectedKeyRing
) internal returns (address keyRing) {
// Only deploy if a key ring doesn't already exist at the expected address.
uint256 size;
assembly { size := extcodesize(expectedKeyRing) }
if (size == 0) {
// Get initialization calldata using the initial user signing key.
bytes memory initializationCalldata = _constructInitializationCalldata(
userSigningKey
);
// Deploy and initialize new user key ring as an Upgrade Beacon proxy.
keyRing = _deployUpgradeBeaconProxyInstance(initializationCalldata);
// Emit an event to signal the creation of the new key ring contract.
emit KeyRingDeployed(keyRing, userSigningKey);
} else {
// Note: specifying an address that was not returned from `getNextKeyRing`
// will cause this assumption to fail. Furthermore, the key ring at the
// expected address may have been modified so that the supplied user
// signing key is no longer a valid key - therefore, treat this helper as
// a way to protect against race conditions, not as a primary mechanism
// for interacting with key ring contracts.
keyRing = expectedKeyRing;
}
}
/**
* @notice Private function to deploy an upgrade beacon proxy via `CREATE2`.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the deployed contract to the implementation set on
* the upgrade beacon during contract creation.
* @return The address of the newly-deployed upgrade beacon proxy.
*/
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
// Place creation code and constructor args of new proxy instance in memory.
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
// Get salt to use during deployment using the supplied initialization code.
(uint256 salt, ) = _getSaltAndTarget(initCode);
// Deploy the new upgrade beacon proxy contract using `CREATE2`.
assembly {
let encoded_data := add(0x20, initCode) // load initialization code.
let encoded_size := mload(initCode) // load the init code's length.
upgradeBeaconProxyInstance := create2( // call `CREATE2` w/ 4 arguments.
callvalue, // forward any supplied endowment.
encoded_data, // pass in initialization code.
encoded_size, // pass in init code's length.
salt // pass in the salt value.
)
// Pass along failure message and revert if contract deployment fails.
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _constructInitializationCalldata(
address userSigningKey
) private pure returns (bytes memory initializationCalldata) {
address[] memory keys = new address[](1);
keys[0] = userSigningKey;
uint8[] memory keyTypes = new uint8[](1);
keyTypes[0] = uint8(3); // Dual key type
// Get initialization calldata from initialize selector & arguments.
initializationCalldata = abi.encodeWithSelector(
_INITIALIZE_SELECTOR, 1, 1, keys, keyTypes
);
}
/**
* @notice Private view function for finding the address of the next upgrade
* beacon proxy that will be deployed, given a particular initialization
* calldata payload.
* @param initializationCalldata bytes The calldata that will be supplied to
* the `DELEGATECALL` from the deployed contract to the implementation set on
* the upgrade beacon during contract creation.
* @return The address of the next upgrade beacon proxy contract with the
* given initialization calldata.
*/
function _computeNextAddress(
bytes memory initializationCalldata
) private view returns (address target) {
// Place creation code and constructor args of the proxy instance in memory.
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
// Get target address using the constructed initialization code.
(, target) = _getSaltAndTarget(initCode);
}
/**
* @notice Private function for determining the salt and the target deployment
* address for the next deployed contract (using `CREATE2`) based on the
* contract creation code.
*/
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
// Get the keccak256 hash of the init code for address derivation.
bytes32 initCodeHash = keccak256(initCode);
// Set the initial nonce to be provided when constructing the salt.
nonce = 0;
// Declare variable for code size of derived address.
uint256 codeSize;
// Loop until an contract deployment address with no code has been found.
while (true) {
target = address( // derive the target deployment address.
uint160( // downcast to match the address type.
uint256( // cast to uint to truncate upper digits.
keccak256( // compute CREATE2 hash using 4 inputs.
abi.encodePacked( // pack all inputs to the hash together.
bytes1(0xff), // pass in the control character.
address(this), // pass in the address of this contract.
nonce, // pass in the salt from above.
initCodeHash // pass in hash of contract creation code.
)
)
)
)
);
// Determine if a contract is already deployed to the target address.
assembly { codeSize := extcodesize(target) }
// Exit the loop if no contract is deployed to the target address.
if (codeSize == 0) {
break;
}
// Otherwise, increment the nonce and derive a new salt.
nonce++;
}
}
/**
* @notice Private function for getting the version of the current key ring
* implementation by using the upgrade beacon to determine the implementation
* and then calling into the returned implementation contract directly.
*/
function _getKeyRingVersion() private view returns (uint256 version) {
// Perform the staticcall into the key ring upgrade beacon.
(bool ok, bytes memory data) = _KEY_RING_UPGRADE_BEACON.staticcall("");
// Revert if underlying staticcall reverts, passing along revert message.
require(ok, string(data));
// Ensure that the data returned from the beacon is the correct length.
require(data.length == 32, "Return data must be exactly 32 bytes.");
// Decode the implementation address from the returned data.
address implementation = abi.decode(data, (address));
// Call into the implementation address directly to get the version.
version = DharmaKeyRingImplementationV0Interface(
implementation
).getVersion();
}
} | * @title DharmaKeyRingFactoryV2 @author 0age @notice This contract deploys new Dharma Key Ring instances as "Upgrade Beacon" proxies that reference a shared implementation contract specified by the Dharma Key Ring Upgrade Beacon contract. It also supplies methods for performing additional operations post-deployment, including setting a second signing key on the keyring and making a withdrawal from the associated smart wallet. Note that the batch operations may fail, or be applied to the wrong keyring, if another caller frontruns them by deploying a keyring to the intended address first. If this becomes an issue, a future version of this factory can remedy this by passing the target deployment address as an additional argument and checking for existence of a contract at that address. This factory builds on V1 by additionally including a helper function for deriving adminActionIDs for keyrings that have not yet been deployed in order to support creation of the signature parameter provided as part of calls to `newKeyRingAndAdditionalKey`./ Use DharmaKeyRing initialize selector to construct initialization calldata. The keyring upgrade beacon is used in order to get the current version. | contract DharmaKeyRingFactoryV2 is DharmaKeyRingFactoryV2Interface {
bytes4 private constant _INITIALIZE_SELECTOR = bytes4(0x30fc201f);
address private constant _KEY_RING_UPGRADE_BEACON = address(
0x0000000000BDA2152794ac8c76B2dc86cbA57cad
);
constructor() public {
DharmaKeyRingInitializer initializer;
require(
initializer.initialize.selector == _INITIALIZE_SELECTOR,
"Incorrect initializer selector supplied."
);
}
function newKeyRing(
address userSigningKey, address targetKeyRing
) external returns (address keyRing) {
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
}
function newKeyRingAndAdditionalKey(
address userSigningKey,
address targetKeyRing,
address additionalSigningKey,
bytes calldata signature
) external returns (address keyRing) {
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
DharmaKeyRingImplementationV0Interface(keyRing).takeAdminAction(
DharmaKeyRingImplementationV0Interface.AdminActionType.AddDualKey,
uint160(additionalSigningKey),
signature
);
}
function newKeyRingAndDaiWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess) {
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
withdrawalSuccess = DharmaSmartWalletImplementationV0Interface(
smartWallet
).withdrawDai(
amount, recipient, minimumActionGas, userSignature, dharmaSignature
);
}
function newKeyRingAndUSDCWithdrawal(
address userSigningKey,
address targetKeyRing,
address smartWallet,
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (address keyRing, bool withdrawalSuccess) {
keyRing = _deployNewKeyRingIfNeeded(userSigningKey, targetKeyRing);
withdrawalSuccess = DharmaSmartWalletImplementationV0Interface(
smartWallet
).withdrawUSDC(
amount, recipient, minimumActionGas, userSignature, dharmaSignature
);
}
function getNextKeyRing(
address userSigningKey
) external view returns (address targetKeyRing) {
require(userSigningKey != address(0), "No user signing key supplied.");
bytes memory initializationCalldata = _constructInitializationCalldata(
userSigningKey
);
targetKeyRing = _computeNextAddress(initializationCalldata);
}
function getFirstKeyRingAdminActionID(
address keyRing, address additionalUserSigningKey
) external view returns (bytes32 adminActionID) {
adminActionID = keccak256(
abi.encodePacked(
keyRing, _getKeyRingVersion(), uint256(0), additionalUserSigningKey
)
);
}
function _deployNewKeyRingIfNeeded(
address userSigningKey, address expectedKeyRing
) internal returns (address keyRing) {
uint256 size;
if (size == 0) {
bytes memory initializationCalldata = _constructInitializationCalldata(
userSigningKey
);
keyRing = _deployUpgradeBeaconProxyInstance(initializationCalldata);
emit KeyRingDeployed(keyRing, userSigningKey);
keyRing = expectedKeyRing;
}
}
assembly { size := extcodesize(expectedKeyRing) }
function _deployNewKeyRingIfNeeded(
address userSigningKey, address expectedKeyRing
) internal returns (address keyRing) {
uint256 size;
if (size == 0) {
bytes memory initializationCalldata = _constructInitializationCalldata(
userSigningKey
);
keyRing = _deployUpgradeBeaconProxyInstance(initializationCalldata);
emit KeyRingDeployed(keyRing, userSigningKey);
keyRing = expectedKeyRing;
}
}
} else {
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
(uint256 salt, ) = _getSaltAndTarget(initCode);
assembly {
)
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
(uint256 salt, ) = _getSaltAndTarget(initCode);
assembly {
)
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _deployUpgradeBeaconProxyInstance(
bytes memory initializationCalldata
) private returns (address upgradeBeaconProxyInstance) {
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
(uint256 salt, ) = _getSaltAndTarget(initCode);
assembly {
)
if iszero(upgradeBeaconProxyInstance) {
returndatacopy(0, 0, returndatasize)
revert(0, returndatasize)
}
}
}
function _constructInitializationCalldata(
address userSigningKey
) private pure returns (bytes memory initializationCalldata) {
address[] memory keys = new address[](1);
keys[0] = userSigningKey;
uint8[] memory keyTypes = new uint8[](1);
initializationCalldata = abi.encodeWithSelector(
_INITIALIZE_SELECTOR, 1, 1, keys, keyTypes
);
}
function _computeNextAddress(
bytes memory initializationCalldata
) private view returns (address target) {
bytes memory initCode = abi.encodePacked(
type(KeyRingUpgradeBeaconProxyV1).creationCode,
abi.encode(initializationCalldata)
);
(, target) = _getSaltAndTarget(initCode);
}
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
bytes32 initCodeHash = keccak256(initCode);
nonce = 0;
uint256 codeSize;
while (true) {
)
)
)
)
);
if (codeSize == 0) {
break;
}
}
}
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
bytes32 initCodeHash = keccak256(initCode);
nonce = 0;
uint256 codeSize;
while (true) {
)
)
)
)
);
if (codeSize == 0) {
break;
}
}
}
assembly { codeSize := extcodesize(target) }
function _getSaltAndTarget(
bytes memory initCode
) private view returns (uint256 nonce, address target) {
bytes32 initCodeHash = keccak256(initCode);
nonce = 0;
uint256 codeSize;
while (true) {
)
)
)
)
);
if (codeSize == 0) {
break;
}
}
}
nonce++;
function _getKeyRingVersion() private view returns (uint256 version) {
(bool ok, bytes memory data) = _KEY_RING_UPGRADE_BEACON.staticcall("");
require(ok, string(data));
require(data.length == 32, "Return data must be exactly 32 bytes.");
address implementation = abi.decode(data, (address));
version = DharmaKeyRingImplementationV0Interface(
implementation
).getVersion();
}
} | 15,868,931 | [
1,
40,
30250,
2540,
653,
10369,
1733,
58,
22,
225,
374,
410,
225,
1220,
6835,
5993,
383,
1900,
394,
463,
30250,
2540,
1929,
25463,
3884,
487,
315,
10784,
4823,
16329,
6,
13263,
716,
2114,
279,
5116,
4471,
6835,
1269,
635,
326,
463,
30250,
2540,
1929,
25463,
17699,
4823,
16329,
6835,
18,
2597,
2546,
1169,
5259,
2590,
364,
14928,
3312,
5295,
1603,
17,
21704,
16,
6508,
3637,
279,
2205,
10611,
498,
603,
326,
20923,
471,
10480,
279,
598,
9446,
287,
628,
326,
3627,
13706,
9230,
18,
3609,
716,
326,
2581,
5295,
2026,
2321,
16,
578,
506,
6754,
358,
326,
7194,
20923,
16,
309,
4042,
4894,
284,
1949,
313,
27595,
2182,
635,
7286,
310,
279,
20923,
358,
326,
12613,
1758,
1122,
18,
971,
333,
12724,
392,
5672,
16,
279,
3563,
1177,
434,
333,
3272,
848,
849,
24009,
333,
635,
9588,
326,
1018,
6314,
1758,
487,
392,
3312,
1237,
471,
6728,
364,
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,
463,
30250,
2540,
653,
10369,
1733,
58,
22,
353,
463,
30250,
2540,
653,
10369,
1733,
58,
22,
1358,
288,
203,
225,
1731,
24,
3238,
5381,
389,
28497,
15641,
67,
4803,
916,
273,
1731,
24,
12,
20,
92,
5082,
7142,
6734,
74,
1769,
203,
203,
225,
1758,
3238,
5381,
389,
3297,
67,
54,
1360,
67,
3079,
24554,
1639,
67,
5948,
2226,
673,
273,
1758,
12,
203,
565,
374,
92,
2787,
9449,
38,
9793,
22,
3600,
5324,
11290,
1077,
28,
71,
6669,
38,
22,
7201,
5292,
7358,
37,
10321,
71,
361,
203,
225,
11272,
203,
203,
225,
3885,
1435,
1071,
288,
203,
565,
463,
30250,
2540,
653,
10369,
14729,
12562,
31,
203,
565,
2583,
12,
203,
1377,
12562,
18,
11160,
18,
9663,
422,
389,
28497,
15641,
67,
4803,
916,
16,
203,
1377,
315,
16268,
12562,
3451,
4580,
1199,
203,
565,
11272,
203,
225,
289,
203,
203,
225,
445,
16670,
10369,
12,
203,
565,
1758,
729,
12322,
653,
16,
1758,
1018,
653,
10369,
203,
225,
262,
3903,
1135,
261,
2867,
498,
10369,
13,
288,
203,
565,
498,
10369,
273,
389,
12411,
1908,
653,
10369,
18299,
12,
1355,
12322,
653,
16,
1018,
653,
10369,
1769,
203,
225,
289,
203,
203,
225,
445,
16670,
10369,
1876,
10552,
653,
12,
203,
565,
1758,
729,
12322,
653,
16,
203,
565,
1758,
1018,
653,
10369,
16,
203,
565,
1758,
3312,
12322,
653,
16,
203,
565,
1731,
745,
892,
3372,
203,
225,
262,
3903,
1135,
261,
2867,
498,
10369,
13,
288,
203,
565,
498,
10369,
273,
389,
12411,
1908,
653,
10369,
18299,
2
] |
./partial_match/56/0x906C660CF518e64D62F367D89a0A4B14d24449DB/sources/MasterLuckyBestCoin.sol | LBCBar with Governance. | contract LBCBar is BEP20('LBC Bar', 'LBCBAR') {
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
_moveDelegates(_delegates[_from], address(0), _amount);
}
constructor(
LuckyBestCoin _cake
LuckyBestCoin public cake;
) public {
cake = _cake;
}
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
cake.transfer(_to, _amount);
}
}
function safeCakeTransfer(address _to, uint256 _amount) public onlyOwner {
uint256 cakeBal = cake.balanceOf(address(this));
if (_amount > cakeBal) {
cake.transfer(_to, cakeBal);
cake.transfer(_to, _amount);
}
}
} else {
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
mapping (address => uint32) public numCheckpoints;
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
mapping (address => uint) public nonces;
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CAKE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CAKE::delegateBySig: invalid nonce");
require(now <= expiry, "CAKE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CAKE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
} else if (cp.fromBlock < blockNumber) {
} else {
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
_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)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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 _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
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)) {
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, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CAKE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
} else {
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;
return chainId;
}
assembly { chainId := chainid() }
}
| 11,160,529 | [
1,
12995,
39,
5190,
598,
611,
1643,
82,
1359,
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,
16351,
511,
16283,
5190,
353,
9722,
52,
3462,
2668,
12995,
39,
16654,
2187,
296,
12995,
8876,
985,
6134,
288,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
12,
2867,
12,
20,
3631,
389,
3771,
1332,
815,
63,
67,
869,
6487,
389,
8949,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
389,
2080,
269,
11890,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
70,
321,
24899,
2080,
16,
389,
8949,
1769,
203,
3639,
389,
8501,
15608,
815,
24899,
3771,
1332,
815,
63,
67,
2080,
6487,
1758,
12,
20,
3631,
389,
8949,
1769,
203,
565,
289,
203,
203,
203,
203,
565,
3885,
12,
203,
3639,
511,
9031,
93,
14173,
27055,
389,
23780,
203,
565,
511,
9031,
93,
14173,
27055,
1071,
276,
911,
31,
203,
565,
262,
1071,
288,
203,
3639,
276,
911,
273,
389,
23780,
31,
203,
565,
289,
203,
203,
565,
445,
4183,
31089,
5912,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1071,
1338,
5541,
288,
203,
3639,
2254,
5034,
276,
911,
38,
287,
273,
276,
911,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
67,
8949,
405,
276,
911,
38,
287,
13,
288,
203,
5411,
276,
911,
18,
13866,
24899,
869,
16,
276,
911,
38,
287,
1769,
203,
5411,
276,
911,
18,
13866,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
289,
2
] |
./full_match/1/0x9f6a8939d5f45d3C51bAF58dadaB04D75b8Da4C1/sources/contracts/MAHAXLocker.sol | @notice Calculate total voting power @dev Adheres to the ERC20 `totalSupply` interface for Aragon compatibility @return Total voting power | function totalSupplyAtT(uint256 t) public view returns (uint256) {
uint256 _epoch = epoch;
Point memory lastPoint = pointHistory[_epoch];
return _supplyAt(lastPoint, t);
}
| 2,959,403 | [
1,
8695,
2078,
331,
17128,
7212,
225,
4052,
27629,
358,
326,
4232,
39,
3462,
1375,
4963,
3088,
1283,
68,
1560,
364,
1201,
346,
265,
8926,
327,
10710,
331,
17128,
7212,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
861,
56,
12,
11890,
5034,
268,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
389,
12015,
273,
7632,
31,
203,
3639,
4686,
3778,
1142,
2148,
273,
1634,
5623,
63,
67,
12015,
15533,
203,
3639,
327,
389,
2859,
1283,
861,
12,
2722,
2148,
16,
268,
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
] |
pragma solidity ^0.5.1;
// This token latch uses buy and sell orders to operate
// Follows the Tr100c protocol
contract ERC20 {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ERC20TokenLatch {
uint64 trade_increment = 1;
uint public fee; // fee for trades
address payable public owner;
address payable public latched_contract;
mapping(uint32 => address payable) public buy_order_owners;
mapping(uint32 => uint256) public buy_order_qty;
mapping(uint32 => uint64) public buy_order_price;
uint32 public num_buy_orders = 0;
uint32 public max_buy_price_idx;
mapping(uint32 => address payable) public sell_order_owners;
mapping(uint32 => uint256) public sell_order_qty;
mapping(uint32 => uint64) public sell_order_price;
uint32 public num_sell_orders = 0;
uint32 public min_sell_price_idx;
function rmBuyOrder(uint32 idx) private {
buy_order_owners[idx]=buy_order_owners[num_buy_orders];
buy_order_qty[idx]=buy_order_qty[num_buy_orders];
buy_order_price[idx]=buy_order_price[num_buy_orders];
num_buy_orders--;
if(max_buy_price_idx==idx){
max_buy_price_idx=0;
for(uint32 i=1;i<num_buy_orders;i++){
if(buy_order_price[max_buy_price_idx]<buy_order_price[i])max_buy_price_idx=i;
}
}
}
function rmSellOrder(uint32 idx) private {
sell_order_owners[idx]=sell_order_owners[num_sell_orders];
sell_order_qty[idx]=sell_order_qty[num_sell_orders];
sell_order_price[idx]=sell_order_price[num_sell_orders];
num_sell_orders--;
if(min_sell_price_idx==idx){
min_sell_price_idx=0;
for(uint32 i=1;i<num_sell_orders;i++){
if(sell_order_price[min_sell_price_idx]>sell_order_price[i])min_sell_price_idx=i;
}
}
}
function addBuyOrder(address payable adr, uint256 qty, uint64 price) private {
buy_order_owners[num_buy_orders] = adr;
buy_order_qty[num_buy_orders] = qty;
buy_order_price[num_buy_orders] = price;
if(price>buy_order_price[max_buy_price_idx])max_buy_price_idx = num_buy_orders;
if(num_buy_orders==0)max_buy_price_idx = 0;
num_buy_orders++;
}
function addSellOrder(address payable adr, uint256 qty, uint64 price) private {
sell_order_owners[num_sell_orders] = adr;
sell_order_qty[num_sell_orders] = qty;
sell_order_price[num_sell_orders] = price;
if(price<sell_order_price[min_sell_price_idx])min_sell_price_idx = num_sell_orders;
if(num_sell_orders==0)min_sell_price_idx = 0;
num_sell_orders++;
}
function maxBuyPrice() public view returns (uint64 price){
return buy_order_price[max_buy_price_idx];
}
function minSellPrice() public view returns (uint64 price){
return sell_order_price[min_sell_price_idx];
}
function getPrice() public view returns (uint64){
if(num_sell_orders==0){
if(num_buy_orders==0)return 1000;
else return maxBuyPrice();
}else if(num_buy_orders==0) return minSellPrice();
return (minSellPrice()+maxBuyPrice())/2;
}
constructor(address payable latch) public {
latched_contract=latch;
owner = msg.sender;
fee = .0001 ether;
}
function balanceOf(address tokenOwner) public view returns (uint balance){
return ERC20(latched_contract).balanceOf(tokenOwner);
}
function totalSupply() public view returns (uint){
return ERC20(latched_contract).totalSupply();
}
function transfer(address target, uint qty) private{
ERC20(latched_contract).transfer(target, qty);
}
function getFee() public view returns (uint){
return fee;
}
function getBuyPrice() public view returns (uint64){
if(num_buy_orders>0)return maxBuyPrice()+trade_increment;
else return getPrice();
}
function getSellPrice() public view returns (uint64){
if(num_sell_orders>0)return minSellPrice()-trade_increment;
else return getPrice();
}
function getSellReturn(uint amount) public view returns (uint){ // ether for selling amount tokens
// computing fees for selling is difficult and expensive, so I'm not doing it. Not worth it.
return (getSellPrice()*amount)/10000;
}
function getBuyCost(uint amount) public view returns (uint){ // ether cost for buying amount tokens
return ((amount*getBuyPrice())/10000) + fee;
}
function buy(uint tokens)public payable{
placeBuyOrder(tokens, getBuyPrice());
}
function placeBuyOrder(uint tokens, uint64 price10000) public payable{
uint cost = fee + ((tokens*price10000)/10000);
require(msg.value>=cost);
// handle fee and any extra funds
msg.sender.transfer(msg.value-cost);
owner.transfer(fee);
uint left = tokens;
// now try to fulfill the order
for(uint32 i=0;i<num_sell_orders;i++){
if(price10000<minSellPrice())
break; // cannot fulfill order because there is not a sell order that would satisfy
if(sell_order_price[i]<=price10000){
// we can trade some!
if(sell_order_qty[i]>left){
// we can trade all!
sell_order_qty[i]-=left;
sell_order_owners[i].transfer((sell_order_price[i]*left)/10000);
transfer(msg.sender, left);
// send the owner any extra funds
owner.transfer(((price10000-sell_order_price[i])*left)/10000);
// order fully fulfilled
return;
}else{
// will complete a single sell order, but buy order will have some left over
uint qty = sell_order_qty[i];
left-=qty;
sell_order_owners[i].transfer((sell_order_price[i]*qty)/10000);
transfer(msg.sender, qty);
// send the owner any extra funds
owner.transfer(((price10000-sell_order_price[i])*qty)/10000);
// delete the order that was completed
rmSellOrder(i);
}
}
}
// if we are here then some of the order is left. Place the order in the queue.
addBuyOrder(msg.sender, left, price10000);
}
function sell(uint tokens)public{
placeSellOrder(tokens, getSellPrice());
}
function placeSellOrder(uint tokens, uint64 price10000) public payable{
require(ERC20(latched_contract).allowance(msg.sender, address(this))>=tokens);
// handle fee and any extra funds
ERC20(latched_contract).transferFrom(msg.sender,address(this),tokens);
// get info needed for trading
uint64 sell_price = price10000;
uint left = tokens;
// now try to fulfill the order
for(uint32 i=0;i<num_buy_orders;i++){
if(sell_price>maxBuyPrice())
break; // cannot fulfill order because there is not a buy order that would satisfy
if(buy_order_price[i]>=sell_price){
// we can trade some!
if(buy_order_qty[i]>left){
// we can trade all!
buy_order_qty[i]-=left;
transfer(buy_order_owners[i],left);
msg.sender.transfer((sell_price*left)/10000);
// send the owner any extra funds
owner.transfer(((buy_order_price[i]-sell_price)*left)/10000);
// order fully fulfilled
return;
}else{
// will complete a single sell order, but buy order will have some left over
uint qty = buy_order_qty[i];
left-=qty;
transfer(buy_order_owners[i],qty);
msg.sender.transfer((sell_price*qty)/10000);
// send the owner any extra funds
owner.transfer(((buy_order_price[i]-sell_price)*qty)/10000);
// delete the order that was completed
rmBuyOrder(i);
}
}
}
// if we are here then some of the order is left. Place the order in the queue.
addSellOrder(msg.sender, left, sell_price);
}
function canBuy(uint amount) public pure returns (bool possible){ // returns true if this amount of token can be bought - does not account for Ethereum account balance
return true;
}
function canSell(uint amount) public pure returns (bool possible){ // returns true if this amount of token can be sold - does not account for token account balance
return true;
}
function get_tradable() public view returns (uint){
return ERC20(latched_contract).totalSupply();
}
function setFee(uint new_fee) public{
require(msg.sender==owner);
fee=new_fee;
}
function destroy() public {
require(msg.sender==owner);
require(address(this).balance<0.1 ether);
require(ERC20(latched_contract).balanceOf(address(this))==0);
selfdestruct(msg.sender);
}
} | computing fees for selling is difficult and expensive, so I'm not doing it. Not worth it. | return (getSellPrice()*amount)/10000;
| 1,065,691 | [
1,
13406,
310,
1656,
281,
364,
357,
2456,
353,
3122,
17551,
471,
19326,
16,
1427,
467,
17784,
486,
9957,
518,
18,
225,
2288,
26247,
518,
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
] | [
1,
1,
1,
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,
202,
202,
2463,
261,
588,
55,
1165,
5147,
1435,
14,
8949,
13176,
23899,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "@openzeppelin/upgrades-core/contracts/Initializable.sol";
import "hardhat/console.sol";
contract Lottery is Initializable{
uint[] public winningLotteryNumber;//开奖号码
uint public lotteryBet;//每次投注的金额
uint256 public lastUserId;//用户投注编号
address public owner;
struct LotteryPlayers {
uint256 id; //用户投注编号
address userAddress; //用户地址
uint8[] lotteryNumber;//彩票号码
}
mapping(uint256 => LotteryPlayers) public idToLotteryPlayers;
mapping(address => uint256[]) public addressToUserIds;
function initialize() public initializer {
lotteryBet = 1 ether;//每次限投 1 ether
lastUserId =0;//用户投注编号
owner = msg.sender;
}
//投注
function throwIn(uint8[] calldata buyLotteryNumber) public payable{
//require(msg.value == lotteryBet, "invalid price");//测试时关闭
require(winningLotteryNumber.length == 0); //还没有开奖
require(buyLotteryNumber.length == 4,'buyLotteryNumber.length == 4');//投注数字是否满足4个
lastUserId++;//用户投注编号
LotteryPlayers memory lotteryPlayers = LotteryPlayers({
id:lastUserId,//用户投注编号
userAddress:msg.sender,//用户地址
lotteryNumber:buyLotteryNumber
});
idToLotteryPlayers[lastUserId]=lotteryPlayers;
addressToUserIds[msg.sender].push(lastUserId);
}
//通过用户投注编号 查询 彩票数组内容
function getLotteryNumberByUserId(uint256 id) public view returns (uint8[] memory) {
require(id <= lastUserId,'id <= lastUserId');//
return idToLotteryPlayers[lastUserId].lotteryNumber;
}
//通过用户地址 查询 该用户所有的投注编号
function getUserIdsByAddress(address userAddress) public view returns (uint256[] memory) {
return addressToUserIds[userAddress];
}
//查询 开奖号码
function getWinningLotteryNumber() public view returns (uint[] memory) {
return winningLotteryNumber;
}
//抽奖 只有管理员有权限
function luckDraw() public {
require(lastUserId != 0); //确保当前盘内有人投注
require(winningLotteryNumber.length == 0);
require(msg.sender == owner);
//利用当前区块的时间戳、挖矿难度和盘内投注彩民数来取随机值
winningLotteryNumber.push(uint(keccak256(abi.encodePacked(block.timestamp,block.difficulty,owner,lastUserId)))%10);
winningLotteryNumber.push(uint(keccak256(abi.encodePacked(block.difficulty,block.timestamp,owner,lastUserId)))%10);
winningLotteryNumber.push(uint(keccak256(abi.encodePacked(block.difficulty,owner,block.timestamp,lastUserId)))%10);
winningLotteryNumber.push(uint(keccak256(abi.encodePacked(block.difficulty,owner,lastUserId,block.timestamp)))%10);
uint256[] storage firstPrize; //一等奖
uint256[] storage secondPrize; //二等奖
for(uint256 i=1;i<=lastUserId;i++){
uint have=0;
for(uint256 j=0;j<4;j++){
if(idToLotteryPlayers[i].lotteryNumber[j]==winningLotteryNumber[j]){
have++;
}
}
if(have==4){
firstPrize.push(i);
}else if(have==3){
secondPrize.push(i);
}
}
if(firstPrize.length>0&&secondPrize.length==0){//如果只有1等奖的用户,平均发放奖励
uint256 _money=address(this).balance/firstPrize.length;
for(uint256 i=0;i<firstPrize.length;i++){
address(uint160(idToLotteryPlayers[firstPrize[i]].userAddress)).transfer(_money);
}
} else if(firstPrize.length==0&&secondPrize.length>0){//如果只有2等奖的用户,平均发放奖励
uint256 _money=address(this).balance/secondPrize.length;
for(uint256 i=0;i<secondPrize.length;i++){
address(uint160(idToLotteryPlayers[secondPrize[i]].userAddress)).transfer(_money);
}
} else if(firstPrize.length>0&&secondPrize.length>0){//1等奖2等奖都有
//余额的80% 1等奖 平均分配
uint256 _money_first=address(this).balance*80/100/firstPrize.length;
//余额的20% 2等奖 平均分配
uint256 _money_second=address(this).balance*20/100/secondPrize.length;
for(uint256 i=0;i<firstPrize.length;i++){
address(uint160(idToLotteryPlayers[firstPrize[i]].userAddress)).transfer(_money_first);
}
for(uint256 i=0;i<secondPrize.length;i++){
address(uint160(idToLotteryPlayers[secondPrize[i]].userAddress)).transfer(_money_second);
}
}
}
} | 投注require(msg.value == lotteryBet, "invalid price");测试时关闭 | function throwIn(uint8[] calldata buyLotteryNumber) public payable{
LotteryPlayers memory lotteryPlayers = LotteryPlayers({
lotteryNumber:buyLotteryNumber
});
idToLotteryPlayers[lastUserId]=lotteryPlayers;
addressToUserIds[msg.sender].push(lastUserId);
}
| 13,099,364 | [
1,
167,
237,
248,
167,
116,
106,
6528,
12,
3576,
18,
1132,
422,
17417,
387,
93,
38,
278,
16,
315,
5387,
6205,
8863,
167,
118,
238,
169,
112,
248,
167,
250,
119,
166,
232,
116,
170,
250,
260,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
604,
382,
12,
11890,
28,
8526,
745,
892,
30143,
48,
352,
387,
93,
1854,
13,
1071,
8843,
429,
95,
203,
3639,
511,
352,
387,
93,
1749,
3907,
3778,
17417,
387,
93,
1749,
3907,
273,
511,
352,
387,
93,
1749,
3907,
12590,
203,
5411,
17417,
387,
93,
1854,
30,
70,
9835,
48,
352,
387,
93,
1854,
203,
3639,
15549,
203,
4202,
612,
774,
48,
352,
387,
93,
1749,
3907,
63,
2722,
10502,
65,
33,
23372,
387,
93,
1749,
3907,
31,
203,
4202,
1758,
774,
1299,
2673,
63,
3576,
18,
15330,
8009,
6206,
12,
2722,
10502,
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
] |
./full_match/1/0x24f5cf5273E56Bb5b02e3adE135dB4c5B4B63741/sources/ChainFarmers.sol | * @notice Returns if presale times are active for a given token/ | function tokenPresaleTimeIsActive(uint256 _tokenId)
public
view
returns (bool)
{
if (tokenUsePresaleTimes[_tokenId] == false) {
return true;
}
return
block.timestamp >= tokenPresaleSaleStartTime[_tokenId] &&
block.timestamp <= tokenPresaleSaleEndTime[_tokenId];
}
| 16,427,992 | [
1,
1356,
309,
4075,
5349,
4124,
854,
2695,
364,
279,
864,
1147,
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,
1147,
12236,
5349,
950,
2520,
3896,
12,
11890,
5034,
389,
2316,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
309,
261,
2316,
3727,
12236,
5349,
10694,
63,
67,
2316,
548,
65,
422,
629,
13,
288,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
3639,
327,
203,
5411,
1203,
18,
5508,
1545,
1147,
12236,
5349,
30746,
13649,
63,
67,
2316,
548,
65,
597,
203,
5411,
1203,
18,
5508,
1648,
1147,
12236,
5349,
30746,
25255,
63,
67,
2316,
548,
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
] |
pragma solidity ^0.4.11;
import "./usingOraclize.sol";
contract Dice is usingOraclize {
uint256 public pwin = 5000; //probability of winning (10000 = 100%)
uint256 public edge = 200; //edge percentage (10000 = 100%)
uint256 public maxWin = 100; //max win (before edge is taken) as percentage of bankroll (10000 = 100%)
uint256 public minBet = 1 finney;
uint256 public maxInvestors = 5; //maximum number of investors
uint256 public houseEdge = 50; //edge percentage (10000 = 100%)
uint256 public divestFee = 50; //divest fee percentage (10000 = 100%)
uint256 public emergencyWithdrawalRatio = 90; //ratio percentage (100 = 100%)
uint256 safeGas = 25000;
uint256 constant ORACLIZE_GAS_LIMIT = 125000;
uint256 constant INVALID_BET_MARKER = 99999;
uint256 constant EMERGENCY_TIMEOUT = 7 days;
struct Investor {
address investorAddress;
uint256 amountInvested;
bool votedForEmergencyWithdrawal;
}
struct Bet {
address playerAddress;
uint256 amountBetted;
uint256 numberRolled;
}
struct WithdrawalProposal {
address toAddress;
uint256 atTime;
}
//Starting at 1
mapping(address => uint256) public investorIDs;
mapping(uint256 => Investor) public investors;
uint256 public numInvestors = 0;
uint256 public invested = 0;
address owner;
address houseAddress;
bool public isStopped;
WithdrawalProposal public proposedWithdrawal;
mapping(bytes32 => Bet) bets;
bytes32[] betsKeys;
uint256 public amountWagered = 0;
uint256 public investorsProfit = 0;
uint256 public investorsLoses = 0;
bool profitDistributed;
event BetWon(
address playerAddress,
uint256 numberRolled,
uint256 amountWon
);
event BetLost(address playerAddress, uint256 numberRolled);
event EmergencyWithdrawalProposed();
event EmergencyWithdrawalFailed(address withdrawalAddress);
event EmergencyWithdrawalSucceeded(
address withdrawalAddress,
uint256 amountWithdrawn
);
event FailedSend(address receiver, uint256 amount);
event ValueIsTooBig();
function Dice(
uint256 pwinInitial,
uint256 edgeInitial,
uint256 maxWinInitial,
uint256 minBetInitial,
uint256 maxInvestorsInitial,
uint256 houseEdgeInitial,
uint256 divestFeeInitial,
uint256 emergencyWithdrawalRatioInitial
) {
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
oraclize_setProof(proofType_TLSNotary | proofStorage_IPFS);
pwin = pwinInitial;
edge = edgeInitial;
maxWin = maxWinInitial;
minBet = minBetInitial;
maxInvestors = maxInvestorsInitial;
houseEdge = houseEdgeInitial;
divestFee = divestFeeInitial;
emergencyWithdrawalRatio = emergencyWithdrawalRatioInitial;
owner = msg.sender;
houseAddress = msg.sender;
}
//SECTION I: MODIFIERS AND HELPER FUNCTIONS
//MODIFIERS
modifier onlyIfNotStopped {
if (isStopped) throw;
_;
}
modifier onlyIfStopped {
if (!isStopped) throw;
_;
}
modifier onlyInvestors {
if (investorIDs[msg.sender] == 0) throw;
_;
}
modifier onlyNotInvestors {
if (investorIDs[msg.sender] != 0) throw;
_;
}
modifier onlyOwner {
if (owner != msg.sender) throw;
_;
}
modifier onlyOraclize {
if (msg.sender != oraclize_cbAddress()) throw;
_;
}
modifier onlyMoreThanMinInvestment {
if (msg.value <= getMinInvestment()) throw;
_;
}
modifier onlyMoreThanZero {
if (msg.value == 0) throw;
_;
}
modifier onlyIfBetSizeIsStillCorrect(bytes32 myid) {
Bet thisBet = bets[myid];
if (
(((thisBet.amountBetted * ((10000 - edge) - pwin)) / pwin) <=
(maxWin * getBankroll()) / 10000)
) {
_;
} else {
bets[myid].numberRolled = INVALID_BET_MARKER;
safeSend(thisBet.playerAddress, thisBet.amountBetted);
return;
}
}
modifier onlyIfValidRoll(bytes32 myid, string result) {
Bet thisBet = bets[myid];
uint256 numberRolled = parseInt(result);
if (
(numberRolled < 1 || numberRolled > 10000) &&
thisBet.numberRolled == 0
) {
bets[myid].numberRolled = INVALID_BET_MARKER;
safeSend(thisBet.playerAddress, thisBet.amountBetted);
return;
}
_;
}
modifier onlyIfInvestorBalanceIsPositive(address currentInvestor) {
if (getBalance(currentInvestor) >= 0) {
_;
}
}
modifier onlyWinningBets(uint256 numberRolled) {
if (numberRolled - 1 < pwin) {
_;
}
}
modifier onlyLosingBets(uint256 numberRolled) {
if (numberRolled - 1 >= pwin) {
_;
}
}
modifier onlyAfterProposed {
if (proposedWithdrawal.toAddress == 0) throw;
_;
}
modifier rejectValue {
if (msg.value != 0) throw;
_;
}
modifier onlyIfProfitNotDistributed {
if (!profitDistributed) {
_;
}
}
modifier onlyIfValidGas(uint256 newGasLimit) {
if (newGasLimit < 25000) throw;
_;
}
modifier onlyIfNotProcessed(bytes32 myid) {
Bet thisBet = bets[myid];
if (thisBet.numberRolled > 0) throw;
_;
}
modifier onlyIfEmergencyTimeOutHasPassed {
if (proposedWithdrawal.atTime + EMERGENCY_TIMEOUT > now) throw;
_;
}
//CONSTANT HELPER FUNCTIONS
function getBankroll() constant returns (uint256) {
return invested + investorsProfit - investorsLoses;
}
function getMinInvestment() constant returns (uint256) {
if (numInvestors == maxInvestors) {
uint256 investorID = searchSmallestInvestor();
return getBalance(investors[investorID].investorAddress);
} else {
return 0;
}
}
function getStatus()
constant
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 bankroll = getBankroll();
uint256 minInvestment = getMinInvestment();
return (
bankroll,
pwin,
edge,
maxWin,
minBet,
amountWagered,
(investorsProfit - investorsLoses),
minInvestment,
betsKeys.length
);
}
function getBet(uint256 id)
constant
returns (
address,
uint256,
uint256
)
{
if (id < betsKeys.length) {
bytes32 betKey = betsKeys[id];
return (
bets[betKey].playerAddress,
bets[betKey].amountBetted,
bets[betKey].numberRolled
);
}
}
function numBets() constant returns (uint256) {
return betsKeys.length;
}
function getMinBetAmount() constant returns (uint256) {
uint256 oraclizeFee =
OraclizeI(OAR.getAddress()).getPrice(
"URL",
ORACLIZE_GAS_LIMIT + safeGas
);
return oraclizeFee + minBet;
}
function getMaxBetAmount() constant returns (uint256) {
uint256 oraclizeFee =
OraclizeI(OAR.getAddress()).getPrice(
"URL",
ORACLIZE_GAS_LIMIT + safeGas
);
uint256 betValue =
((maxWin * getBankroll()) * pwin) / (10000 * (10000 - edge - pwin));
return betValue + oraclizeFee;
}
function getLosesShare(address currentInvestor) constant returns (uint256) {
return
(investors[investorIDs[currentInvestor]].amountInvested *
(investorsLoses)) / invested;
}
function getProfitShare(address currentInvestor)
constant
returns (uint256)
{
return
(investors[investorIDs[currentInvestor]].amountInvested *
(investorsProfit)) / invested;
}
function getBalance(address currentInvestor) constant returns (uint256) {
return
investors[investorIDs[currentInvestor]].amountInvested +
getProfitShare(currentInvestor) -
getLosesShare(currentInvestor);
}
function searchSmallestInvestor() constant returns (uint256) {
uint256 investorID = 1;
for (uint256 i = 1; i <= numInvestors; i++) {
if (
getBalance(investors[i].investorAddress) <
getBalance(investors[investorID].investorAddress)
) {
investorID = i;
}
}
return investorID;
}
// PRIVATE HELPERS FUNCTION
function safeSend(address addr, uint256 value) private {
if (this.balance < value) {
ValueIsTooBig();
return;
}
if (!(addr.call.gas(safeGas).value(value)())) {
FailedSend(addr, value);
if (addr != houseAddress) {
//Forward to house address all change
if (!(houseAddress.call.gas(safeGas).value(value)()))
FailedSend(houseAddress, value);
}
}
}
function addInvestorAtID(uint256 id) private {
investorIDs[msg.sender] = id;
investors[id].investorAddress = msg.sender;
investors[id].amountInvested = msg.value;
invested += msg.value;
}
function profitDistribution() private onlyIfProfitNotDistributed {
uint256 copyInvested;
for (uint256 i = 1; i <= numInvestors; i++) {
address currentInvestor = investors[i].investorAddress;
uint256 profitOfInvestor = getProfitShare(currentInvestor);
uint256 losesOfInvestor = getLosesShare(currentInvestor);
investors[i].amountInvested += profitOfInvestor - losesOfInvestor;
copyInvested += investors[i].amountInvested;
}
delete investorsProfit;
delete investorsLoses;
invested = copyInvested;
profitDistributed = true;
}
// SECTION II: BET & BET PROCESSING
function() {
bet();
}
function bet() onlyIfNotStopped onlyMoreThanZero {
uint256 oraclizeFee =
OraclizeI(OAR.getAddress()).getPrice(
"URL",
ORACLIZE_GAS_LIMIT + safeGas
);
uint256 betValue = msg.value - oraclizeFee;
if (
(((betValue * ((10000 - edge) - pwin)) / pwin) <=
(maxWin * getBankroll()) / 10000) && (betValue >= minBet)
) {
// encrypted arg: '\n{"jsonrpc":2.0,"method":"generateSignedIntegers","params":{"apiKey":"YOUR_API_KEY","n":1,"min":1,"max":10000},"id":1}'
bytes32 myid =
oraclize_query(
"URL",
"json(https://api.random.org/json-rpc/1/invoke).result.random.data.0",
"BBX1PCQ9134839wTz10OWxXCaZaGk92yF6TES8xA+8IC7xNBlJq5AL0uW3rev7IoApA5DMFmCfKGikjnNbNglKKvwjENYPB8TBJN9tDgdcYNxdWnsYARKMqmjrJKYbBAiws+UU6HrJXUWirO+dBSSJbmjIg+9vmBjSq8KveiBzSGmuQhu7/hSg5rSsSP/r+MhR/Q5ECrOHi+CkP/qdSUTA/QhCCjdzFu+7t3Hs7NU34a+l7JdvDlvD8hoNxyKooMDYNbUA8/eFmPv2d538FN6KJQp+RKr4w4VtAMHdejrLM=",
ORACLIZE_GAS_LIMIT + safeGas
);
bets[myid] = Bet(msg.sender, betValue, 0);
betsKeys.push(myid);
} else {
throw;
}
}
function __callback(
bytes32 myid,
string result,
bytes proof
)
onlyOraclize
onlyIfNotProcessed(myid)
onlyIfValidRoll(myid, result)
onlyIfBetSizeIsStillCorrect(myid)
{
Bet thisBet = bets[myid];
uint256 numberRolled = parseInt(result);
bets[myid].numberRolled = numberRolled;
isWinningBet(thisBet, numberRolled);
isLosingBet(thisBet, numberRolled);
amountWagered += thisBet.amountBetted;
delete profitDistributed;
}
function isWinningBet(Bet thisBet, uint256 numberRolled)
private
onlyWinningBets(numberRolled)
{
uint256 winAmount = (thisBet.amountBetted * (10000 - edge)) / pwin;
BetWon(thisBet.playerAddress, numberRolled, winAmount);
safeSend(thisBet.playerAddress, winAmount);
investorsLoses += (winAmount - thisBet.amountBetted);
}
function isLosingBet(Bet thisBet, uint256 numberRolled)
private
onlyLosingBets(numberRolled)
{
BetLost(thisBet.playerAddress, numberRolled);
safeSend(thisBet.playerAddress, 1);
investorsProfit +=
((thisBet.amountBetted - 1) * (10000 - houseEdge)) /
10000;
uint256 houseProfit =
((thisBet.amountBetted - 1) * (houseEdge)) / 10000;
safeSend(houseAddress, houseProfit);
}
//SECTION III: INVEST & DIVEST
function increaseInvestment()
onlyIfNotStopped
onlyMoreThanZero
onlyInvestors
{
profitDistribution();
investors[investorIDs[msg.sender]].amountInvested += msg.value;
invested += msg.value;
}
function newInvestor()
payable
onlyIfNotStopped
onlyMoreThanZero
onlyNotInvestors
onlyMoreThanMinInvestment
{
profitDistribution();
if (numInvestors == maxInvestors) {
uint256 smallestInvestorID = searchSmallestInvestor();
divest(investors[smallestInvestorID].investorAddress);
}
numInvestors++;
addInvestorAtID(numInvestors);
}
function divest() onlyInvestors rejectValue {
divest(msg.sender);
}
function divest(address currentInvestor)
private
onlyIfInvestorBalanceIsPositive(currentInvestor)
{
profitDistribution();
uint256 currentID = investorIDs[currentInvestor];
uint256 amountToReturn = getBalance(currentInvestor);
invested -= investors[currentID].amountInvested;
uint256 divestFeeAmount = (amountToReturn * divestFee) / 10000;
amountToReturn -= divestFeeAmount;
delete investors[currentID];
delete investorIDs[currentInvestor];
//Reorder investors
if (currentID != numInvestors) {
// Get last investor
Investor lastInvestor = investors[numInvestors];
//Set last investor ID to investorID of divesting account
investorIDs[lastInvestor.investorAddress] = currentID;
//Copy investor at the new position in the mapping
investors[currentID] = lastInvestor;
//Delete old position in the mappping
delete investors[numInvestors];
}
numInvestors--;
safeSend(currentInvestor, amountToReturn);
safeSend(houseAddress, divestFeeAmount);
}
function forceDivestOfAllInvestors() onlyOwner rejectValue {
uint256 copyNumInvestors = numInvestors;
for (uint256 i = 1; i <= copyNumInvestors; i++) {
divest(investors[1].investorAddress);
}
}
/*
The owner can use this function to force the exit of an investor from the
contract during an emergency withdrawal in the following situations:
- Unresponsive investor
- Investor demanding to be paid in other to vote, the facto-blackmailing
other investors
*/
function forceDivestOfOneInvestor(address currentInvestor)
onlyOwner
onlyIfStopped
rejectValue
{
divest(currentInvestor);
//Resets emergency withdrawal proposal. Investors must vote again
delete proposedWithdrawal;
}
//SECTION IV: CONTRACT MANAGEMENT
function stopContract() onlyOwner rejectValue {
isStopped = true;
}
function resumeContract() onlyOwner rejectValue {
isStopped = false;
}
function changeHouseAddress(address newHouse) onlyOwner rejectValue {
houseAddress = newHouse;
}
function changeOwnerAddress(address newOwner) onlyOwner rejectValue {
owner = newOwner;
}
function changeGasLimitOfSafeSend(uint256 newGasLimit)
onlyOwner
onlyIfValidGas(newGasLimit)
rejectValue
{
safeGas = newGasLimit;
}
//SECTION V: EMERGENCY WITHDRAWAL
function voteEmergencyWithdrawal(bool vote)
onlyInvestors
onlyAfterProposed
onlyIfStopped
rejectValue
{
investors[investorIDs[msg.sender]].votedForEmergencyWithdrawal = vote;
}
function proposeEmergencyWithdrawal(address withdrawalAddress)
onlyIfStopped
onlyOwner
rejectValue
{
//Resets previous votes
for (uint256 i = 1; i <= numInvestors; i++) {
delete investors[i].votedForEmergencyWithdrawal;
}
proposedWithdrawal = WithdrawalProposal(withdrawalAddress, now);
EmergencyWithdrawalProposed();
}
function executeEmergencyWithdrawal()
onlyOwner
onlyAfterProposed
onlyIfStopped
onlyIfEmergencyTimeOutHasPassed
rejectValue
{
uint256 numOfVotesInFavour;
uint256 amountToWithdrawal = this.balance;
for (uint256 i = 1; i <= numInvestors; i++) {
if (investors[i].votedForEmergencyWithdrawal == true) {
numOfVotesInFavour++;
delete investors[i].votedForEmergencyWithdrawal;
}
}
if (
numOfVotesInFavour >=
(emergencyWithdrawalRatio * numInvestors) / 100
) {
if (!proposedWithdrawal.toAddress.send(this.balance)) {
EmergencyWithdrawalFailed(proposedWithdrawal.toAddress);
} else {
EmergencyWithdrawalSucceeded(
proposedWithdrawal.toAddress,
amountToWithdrawal
);
}
} else {
throw;
}
}
}
| /Resets emergency withdrawal proposal. Investors must vote again | The owner can use this function to force the exit of an investor from the
contract during an emergency withdrawal in the following situations:
- Unresponsive investor
- Investor demanding to be paid in other to vote, the facto-blackmailing
other investors
function forceDivestOfOneInvestor(address currentInvestor)
onlyOwner
onlyIfStopped
rejectValue
{
divest(currentInvestor);
delete proposedWithdrawal;
}
| 7,328,443 | [
1,
19,
18900,
801,
24530,
598,
9446,
287,
14708,
18,
5454,
395,
1383,
1297,
12501,
3382,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1021,
3410,
848,
999,
333,
445,
358,
2944,
326,
2427,
434,
392,
2198,
395,
280,
628,
326,
203,
565,
6835,
4982,
392,
801,
24530,
598,
9446,
287,
316,
326,
3751,
28474,
30,
203,
3639,
300,
1351,
455,
24727,
2198,
395,
280,
203,
3639,
300,
5454,
395,
280,
23653,
310,
358,
506,
30591,
316,
1308,
358,
12501,
16,
326,
5410,
83,
17,
11223,
4408,
310,
203,
3639,
1308,
2198,
395,
1383,
203,
565,
445,
2944,
7244,
395,
951,
3335,
3605,
395,
280,
12,
2867,
783,
3605,
395,
280,
13,
203,
3639,
1338,
5541,
203,
3639,
1338,
2047,
15294,
203,
3639,
4925,
620,
203,
565,
288,
203,
3639,
3739,
395,
12,
2972,
3605,
395,
280,
1769,
203,
3639,
1430,
20084,
1190,
9446,
287,
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
] |
./full_match/43114/0xeCfE536a209e405Db19887830b366E397f5B917a/sources/token.sol | split the contract balance into halves 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 swap tokens for ETH how much ETH did we just swap into? | function swapAndLiquify(uint256 contractTokenBalance) public {
uint256 half = contractTokenBalance.div(2);
uint256 otherHalf = contractTokenBalance.sub(half);
uint256 initialBalance = address(this).balance;
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
}
| 4,563,941 | [
1,
4939,
326,
6835,
11013,
1368,
19514,
3324,
7477,
326,
6835,
1807,
783,
512,
2455,
11013,
18,
333,
353,
1427,
716,
732,
848,
7477,
8950,
326,
3844,
434,
512,
2455,
716,
326,
7720,
3414,
16,
471,
486,
1221,
326,
4501,
372,
24237,
871,
2341,
1281,
512,
2455,
716,
711,
2118,
10036,
3271,
358,
326,
6835,
7720,
2430,
364,
512,
2455,
3661,
9816,
512,
2455,
5061,
732,
2537,
7720,
1368,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
1876,
48,
18988,
1164,
12,
11890,
5034,
6835,
1345,
13937,
13,
1071,
225,
288,
203,
3639,
2254,
5034,
8816,
273,
6835,
1345,
13937,
18,
2892,
12,
22,
1769,
203,
3639,
2254,
5034,
1308,
16168,
273,
6835,
1345,
13937,
18,
1717,
12,
20222,
1769,
203,
203,
3639,
2254,
5034,
2172,
13937,
273,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
203,
3639,
2254,
5034,
394,
13937,
273,
1758,
12,
2211,
2934,
12296,
18,
1717,
12,
6769,
13937,
1769,
203,
203,
3639,
527,
48,
18988,
24237,
12,
3011,
16168,
16,
394,
13937,
1769,
203,
540,
203,
3639,
3626,
12738,
1876,
48,
18988,
1164,
12,
20222,
16,
394,
13937,
16,
1308,
16168,
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
] |
pragma solidity ^0.4.18;
/**
* @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 Base Token contract - Functions to be implemented by token contracts.
contract Token {
/*
* Implements ERC 20 standard.
* https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md
* https://github.com/ethereum/EIPs/issues/20
*
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
* https://github.com/ethereum/EIPs/issues/223
*/
/*
* ERC 20
*/
function balanceOf(address _owner) public constant returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function burn(uint num) public;
/*
* ERC 223
*/
function transfer(address _to, uint256 _value, bytes _data) public returns (bool success);
/*
* Events
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Burn(address indexed _burner, uint _value);
// There is no ERC223 compatible Transfer event, with `_data` included.
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes[3] memory args = [unonce, nbytes, sessionKeyHash];
bytes32 queryId = oraclize_query(_delay, "random", args, _customGasLimit);
oraclize_randomDS_setCommitment(queryId, keccak256(bytes8(_delay), args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
/**
* @title Ico
* @dev Ico is a base contract for managing a token crowdsale.
* Crowdsales
*/
contract Ico is usingOraclize {
using SafeMath for uint256;
/**
* Section 1
* - Variables
*/
/* Section 1.1 crowdsale key variables */
// The token being sold
Token public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where ETH funds are sent
address public wallet;
// owner of this contract
address public owner;
// How many PHI tokens to sell (in sphi)
uint256 public MAX_TOKENS = 7881196 * 10**18;
// Keep track of sold tokens
uint256 public tokensSold = 0;
// Keep track of tokens sent to whitelisted addresses
uint256 public tokensFinalized = 0;
/* Section 1.2 rate/price variables */
// ETH/USD rate
uint256 public ethUsd;
/**
* Phi rate in USD multiplied by 10**18
* because of Solidity float limitations,
* see http://solidity.readthedocs.io/en/v0.4.19/types.html?highlight=Fixed%20Point%20Numbers#fixed-point-numbers
*/
uint256 public phiRate = 1618033990000000000; // ico fixed price 1.61803399 * 10**18
/* Section 1.3 oracle related variables */
// keep track of the last ETH/USD update
uint256 public lastOracleUpdate;
// set default ETH/USD update interval (in seconds)
uint256 public intervalUpdate;
// custom oraclize_query gas cost (wei), expected gas usage is ~110k
uint256 public ORACLIZE_GAS_LIMIT = 145000;
/* Section 1.4 variables to keep KYC and balance state */
// amount of raised money in wei
uint256 public weiRaised;
// keep track of addresses that are allowed to keep tokens
mapping(address => bool) public isWhitelisted;
// keep track of investors (token balance)
mapping(address => uint256) public balancesToken;
// keep track of invested amount (wei balance)
mapping(address => uint256) public balancesWei;
/**
* Section 2
* - Enums
*/
// Describes current crowdsale stage
enum Stage
{
ToInitialize, // [0] ico has not been initialized
Waiting, // [1] ico is waiting start time
Running, // [2] ico is running (between start time and end time)
Paused, // [3] ico has been paused
Finished, // [4] ico has been finished (but not finalized)
Finalized // [5] ico has been finalized
}
Stage public currentStage = Stage.ToInitialize;
/**
* Section 3
* - Events
*/
/**
* 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);
/**
* event to emit when a new rate is received from Oraclize
* @param newRate Rate received in WEI
* @param timeRecv When the rate was received
*/
event LogRateUpdate(uint newRate, uint timeRecv);
/**
* event to emit in case the contract needs balance (for Oraclize queries)
*/
event LogBalanceRequired();
/**
* event to notify initialize
*/
event LogCrowdsaleInit();
/**
* Section 4
* - Modifiers
*/
/*
Check if a purchase can be made, check startTime, endTime
and update Stage if so
*/
modifier validPurchase {
bool withinPeriod = now >= startTime && now <= endTime;
require(msg.value > 0 && withinPeriod && startTime != 0);
/*
Update current stage only if the previous stage is `Waiting`
and we are within the crowdsale period, used to automatically
update the stage by an investor
*/
if (withinPeriod == true && currentStage == Stage.Waiting) {
currentStage = Stage.Running;
}
_;
}
// Allow only the owner of this contract
modifier onlyOwner {
require(msg.sender == owner);
_;
}
// Allow only if is close to start time or if is it running
modifier closeOrDuringCrowdsale {
require(now >= startTime - intervalUpdate);
require(currentStage == Stage.Running || currentStage == Stage.Waiting);
_;
}
// Check if the provided stage is the current one
modifier mustBeAtStage (Stage stageNeeded) {
require(stageNeeded == currentStage);
_;
}
/**
* @dev Constructor
* @param _wallet Where to send ETH collected from the ico
*/
function Ico(address _wallet) public {
require(phiRate > 0 && startTime == 0);
require(_wallet != address(0));
// update global variable
wallet = _wallet;
owner = msg.sender;
currentStage = Stage.ToInitialize;
// set Oraclize gas price (for __callback)
oraclize_setCustomGasPrice(2500000000); // 2.5 gwei instead of 20 gwei
}
/**
* @dev Used to init crowdsale, set start-end time, start usd rate update
* @notice You must send some ETH to cover the oraclize_query fees
* @param _startTime Start of the crowdsale (UNIX timestamp)
* @param _endTime End of the crowdsale (UNIX timestamp)
* @param _token Address of the PHI ERC223 Token
*/
function initializeCrowdsale(
uint256 _startTime,
uint256 _endTime,
address _token,
uint256 _intervalUpdate
)
public
payable
onlyOwner
mustBeAtStage(Stage.ToInitialize)
{
require(_startTime >= now);
require(_endTime >= _startTime);
require(_token != address(0));
require(msg.value > 0);
require(isContract(_token) == true);
// interval update must be above or equal to 5 seconds
require(_intervalUpdate >= 5);
// update global variables
startTime = _startTime;
endTime = _endTime;
token = Token(_token);
intervalUpdate = _intervalUpdate;
// update stage
currentStage = Stage.Waiting;
/*
start to fetch ETH/USD price `intervalUpdate` before the `startTime`,
30 seconds is added because Oraclize takes time to call the __callback
*/
updateEthRateWithDelay(startTime - (intervalUpdate + 30));
LogCrowdsaleInit();
// check amount of tokens held by this contract matches MAX_TOKENS
assert(token.balanceOf(address(this)) == MAX_TOKENS);
}
/* Oraclize related functions */
/**
* @dev Callback function used by Oraclize to update the price.
* @notice ETH/USD rate is receivd and converted to wei, this
* functions is used also to automatically update the stage status
* @param myid Unique identifier for Oraclize queries
* @param result Result of the requested query
*/
function __callback(
bytes32 myid,
string result
)
public
closeOrDuringCrowdsale
{
if (msg.sender != oraclize_cbAddress()) revert();
// parse to int and multiply by 10**18 to allow math operations
uint256 usdRate = parseInt(result, 18);
// do not allow 0
require(usdRate > 0);
ethUsd = usdRate;
LogRateUpdate(ethUsd, now);
// check if time is over
if (hasEnded() == true) {
currentStage = Stage.Finished;
} else {
updateEthRate();
lastOracleUpdate = now;
}
}
/**
* @dev Update ETH/USD rate manually in case Oraclize is not
* calling by our contract
* @notice An integer is required (e.g. 870, 910), this function
* will also multiplicate by 10**18
* @param _newEthUsd New ETH/USD rate integer
*/
function updateEthUsdManually (uint _newEthUsd) public onlyOwner {
require(_newEthUsd > 0);
uint256 newRate = _newEthUsd.mul(10**18);
require(newRate > 0);
ethUsd = newRate;
}
/**
* @dev Used to recursively call the oraclize query
* @notice This function will not throw in case the
* interval update is exceeded, in this way the latest
* update made to the ETH/USD rate is kept
*/
function updateEthRate () internal {
// prevent multiple updates
if(intervalUpdate > (now - lastOracleUpdate)) {}
else {
updateEthRateWithDelay(intervalUpdate);
}
}
/**
* @dev Change interval update
* @param newInterval New interval rate (in seconds)
*/
function changeIntervalUpdate (uint newInterval) public onlyOwner {
require(newInterval >= 5);
intervalUpdate = newInterval;
}
/**
* @dev Helper function around oraclize_query
* @notice Call oraclize_query with a delay in seconds
* @param delay Delay in seconds
*/
function updateEthRateWithDelay (uint delay) internal {
// delay cannot be below 5 seconds (too fast)
require(delay >= 5);
if (oraclize_getPrice("URL", ORACLIZE_GAS_LIMIT) > this.balance) {
// Notify that we need a top up
LogBalanceRequired();
} else {
// Get ETH/USD rate from kraken API
oraclize_query(
delay,
"URL",
"json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0",
ORACLIZE_GAS_LIMIT
);
}
}
/**
* @dev Allow owner to force rate update
* @param delay Delay in seconds of oraclize_query, can be set to 5 (minimum)
*/
function forceOraclizeUpdate (uint256 delay) public onlyOwner {
updateEthRateWithDelay(delay);
}
/**
* @dev Change Oraclize gas limit (used in oraclize_query)
* @notice To be used in case the default gas cost is too low
* @param newGas New gas to use (in wei)
*/
function changeOraclizeGas(uint newGas) public onlyOwner {
require(newGas > 0 && newGas <= 4000000);
ORACLIZE_GAS_LIMIT = newGas;
}
/**
* @dev Change Oraclize gas price
* @notice To be used in case the default gas price is too low
* @param _gasPrice Gas price in wei
*/
function changeOraclizeGasPrice(uint _gasPrice) public onlyOwner {
require(_gasPrice >= 1000000000); // minimum 1 gwei
oraclize_setCustomGasPrice(_gasPrice);
}
/**
* @dev Top up balance
* @notice This function must be used **only if
* this contract balance is too low for oraclize_query
* to be executed**
* @param verifyCode Used only to allow people that read
* the notice (not accidental)
*/
function topUpBalance (uint verifyCode) public payable mustBeAtStage(Stage.Running) {
// value is required
require(msg.value > 0);
// make sure only the people that read
// this can use the function
require(verifyCode == 28391728448);
}
/**
* @dev Withdraw balance of this contract to the `wallet` address
* @notice Used only if there are some leftover
* funds (because of topUpBalance)
*/
function withdrawBalance() public mustBeAtStage(Stage.Finalized) {
wallet.transfer(this.balance);
}
/* Invest related functions */
/**
* @dev Fallback function, to be used to purchase tokens
*/
function () public payable validPurchase mustBeAtStage(Stage.Running) {
require(msg.sender != address(0));
// cannot be a contract
require(isContract(msg.sender) == false);
address beneficiary = msg.sender;
uint256 weiAmount = msg.value;
// calculate token amount to be transfered
uint256 tokens = getTokenAmount(weiAmount);
require(tokens > 0);
// check if we are below MAX_TOKENS
require(tokensSold.add(tokens) <= MAX_TOKENS);
// update tokens sold
tokensSold = tokensSold.add(tokens);
// update total wei counter
weiRaised = weiRaised.add(weiAmount);
// update balance of the beneficiary
balancesToken[beneficiary] = balancesToken[beneficiary].add(tokens);
balancesWei[beneficiary] = balancesWei[beneficiary].add(weiAmount);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
// forward ETH
forwardFunds();
}
/**
* @dev send ether to the fund collection wallet
*/
function forwardFunds() internal {
wallet.transfer(msg.value);
}
/* Finalize/whitelist functions */
/**
* @dev Add multiple whitelisted addresses
* @notice Must be called after the crowdsale has finished
* @param investors Array or investors to enable
*/
function addWhitelistAddrByList (address[] investors) public onlyOwner mustBeAtStage(Stage.Finished) {
for(uint256 i = 0; i < investors.length; i++) {
addWhitelistAddress(investors[i]);
}
}
/**
* @dev Whitelist a specific address
* @notice This is mainly an helper function but can be useful in
* case the `addWhitelistAddrs` loop has issues
* @param investor Investor to whitelist
*/
function addWhitelistAddress (address investor) public onlyOwner mustBeAtStage(Stage.Finished) {
require(investor != address(0) && investor != address(this));
require(isWhitelisted[investor] == false);
require(balancesToken[investor] > 0);
isWhitelisted[investor] = true;
}
/**
* @dev Remove an address from whitelist
*/
function removeWhitelistedAddress (address toRemove) public onlyOwner mustBeAtStage(Stage.Finished) {
require(isWhitelisted[toRemove] == true);
isWhitelisted[toRemove] = false;
}
/**
* @dev Finalize crowdsale with investors array
* @notice Transfers tokens to whitelisted addresses
*/
function finalizeInvestorsByList(address[] investors) public onlyOwner mustBeAtStage(Stage.Finished) {
for(uint256 i = 0; i < investors.length; i++) {
finalizeSingleInvestor(investors[i]);
}
}
/**
* @dev Finalize a specific investor
* @notice This is mainly an helper function to `finalize` but
* can be used if `finalize` has issues with the loop
* @param investorAddr Address to finalize
*/
function finalizeSingleInvestor(address investorAddr) public onlyOwner mustBeAtStage(Stage.Finished) {
require(investorAddr != address(0) && investorAddr != address(this));
require(balancesToken[investorAddr] > 0);
require(isWhitelisted[investorAddr] == true);
// save data into variables
uint256 balanceToTransfer = balancesToken[investorAddr];
// reset current state
balancesToken[investorAddr] = 0;
isWhitelisted[investorAddr] = false;
// transfer token to the investor address and the balance
// that we have recorded before
require(token.transfer(investorAddr, balanceToTransfer));
// update tokens sent
tokensFinalized = tokensFinalized.add(balanceToTransfer);
assert(tokensFinalized <= MAX_TOKENS);
}
/**
* @dev Burn unsold tokens
* @notice Call this function after finalizing
*/
function burnRemainingTokens() public onlyOwner mustBeAtStage(Stage.Finalized) {
// should always be true
require(MAX_TOKENS >= tokensFinalized);
uint unsold = MAX_TOKENS.sub(tokensFinalized);
if (unsold > 0) {
token.burn(unsold);
}
}
/**
* @dev Burn all remaining tokens held by this contract
* @notice Get the token balance of this contract and burns all tokens
*/
function burnAllTokens() public onlyOwner mustBeAtStage(Stage.Finalized) {
uint thisTokenBalance = token.balanceOf(address(this));
if (thisTokenBalance > 0) {
token.burn(thisTokenBalance);
}
}
/**
* @dev Allow to change the current stage
* @param newStage New stage
*/
function changeStage (Stage newStage) public onlyOwner {
currentStage = newStage;
}
/**
* @dev ico status (based only on time)
* @return true if crowdsale event has ended
*/
function hasEnded() public constant returns (bool) {
return now > endTime && startTime != 0;
}
/* Price functions */
/**
* @dev Get current ETH/PHI rate (1 ETH = getEthPhiRate() PHI)
* @notice It divides (ETH/USD rate) / (PHI/USD rate), use the
* custom function `getEthPhiRate(false)` if you want a more
* accurate rate
* @return ETH/PHI rate
*/
function getEthPhiRate () public constant returns (uint) {
// 1/(ETH/PHI rate) * (ETH/USD rate) should return PHI rate
// multiply by 1000 to keep decimals from the division
return ethUsd.div(phiRate);
}
/**
* @dev Get current kETH/PHI rate (1000 ETH = getkEthPhiRate() PHI)
* used to get a more accurate rate (by not truncating decimals)
* @notice It divides (ETH/USD rate) / (PHI/USD rate)
* @return kETH/PHI rate
*/
function getkEthPhiRate () public constant returns (uint) {
// 1/(kETH/PHI rate) * (ETH/USD rate) should return PHI rate
// multiply by 1000 to keep decimals from the division, and return kEth/PHI rate
return ethUsd.mul(1000).div(phiRate);
}
/**
* @dev Calculate amount of token based on wei amount
* @param weiAmount Amount of wei
* @return Amount of PHI tokens
*/
function getTokenAmount(uint256 weiAmount) public constant returns(uint256) {
// get kEth rate to keep decimals
uint currentKethRate = getkEthPhiRate();
// divide by 1000 to revert back the multiply
return currentKethRate.mul(weiAmount).div(1000);
}
/* Helper functions for token balance */
/**
* @dev Returns how many tokens an investor has
* @param investor Investor to look for
* @return Balance of the investor
*/
function getInvestorBalance(address investor) external constant returns (uint) {
return balancesToken[investor];
}
/**
* @dev Returns how many wei an investor has invested
* @param investor Investor to look for
* @return Balance of the investor
*/
function getInvestorWeiBalance(address investor) external constant returns (uint) {
return balancesWei[investor];
}
/**
* @dev Check if an address is a contract
* @param addr Address to check
* @return True if is a contract
*/
function isContract(address addr) public constant returns (bool) {
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
/* Ico engine compatible functions */
/**
* @dev Return `started` state
* false if the crowdsale is not started,
* true if the crowdsale is started and running,
* true if the crowdsale is completed
* @return crowdsale state
*/
function started() public view returns(bool) {
if ((uint8(currentStage) >= 2 || now >= startTime && now <= endTime) && uint8(currentStage) != 3) return true;
return false;
}
/**
* @dev Return if crowdsale ended
* false if the crowdsale is not started,
* false if the crowdsale is started and running,
* true if the crowdsale is completed
* @return ended state
*/
function ended() public view returns(bool) {
if (tokensSold == MAX_TOKENS) return true;
if (uint8(currentStage) >= 4) return true;
return hasEnded();
}
/**
* @dev returns the total number of the tokens available for the sale,
* must not change when the crowdsale is started
* @return total tokens in sphi
*/
function totalTokens() public view returns(uint) {
return MAX_TOKENS;
}
/**
* @dev returns the number of the tokens available for the crowdsale.
* At the moment that the crowdsale starts it must be equal to totalTokens(),
* then it will decrease. It is used to calculate the
* percentage of sold tokens as remainingTokens() / totalTokens()
* @return Remaining tokens in sphi
*/
function remainingTokens() public view returns(uint) {
return MAX_TOKENS.sub(tokensSold);
}
/**
* @dev return the price as number of tokens released for each ether
* @return amount in sphi for 1 ether
*/
function price() public view returns(uint) {
return getTokenAmount(1 ether);
}
} | * @dev Withdraw balance of this contract to the `wallet` address @notice Used only if there are some leftover funds (because of topUpBalance)/ | function withdrawBalance() public mustBeAtStage(Stage.Finalized) {
wallet.transfer(this.balance);
}
| 12,666,328 | [
1,
1190,
9446,
11013,
434,
333,
6835,
358,
326,
1375,
19177,
68,
1758,
225,
10286,
1338,
309,
1915,
854,
2690,
29709,
284,
19156,
261,
26274,
434,
1760,
1211,
13937,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
598,
9446,
13937,
1435,
1071,
1297,
1919,
861,
8755,
12,
8755,
18,
7951,
1235,
13,
288,
203,
565,
9230,
18,
13866,
12,
2211,
18,
12296,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.23;
/**
* @author Dan Emmons at Loci.io
*/
/**
* @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 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 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 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 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;
}
}
contract LOCIcredits is Ownable, Contactable {
using SafeMath for uint256;
StandardToken token; // LOCIcoin deployed contract
mapping (address => bool) internal allowedOverrideAddresses;
mapping (string => LOCIuser) users;
string[] userKeys;
uint256 userCount;
// convenience for accounting
event UserAdded( string id, uint256 time );
// core usage: increaseCredits, reduceCredits, buyCreditsAndSpend, buyCreditsAndSpendAndRecover
event CreditsAdjusted( string id, uint8 adjustment, uint256 value, uint8 reason, address register );
// special usage: transferCreditsInternally (only required in the event of a user that created multiple accounts)
event CreditsTransferred( string id, uint256 value, uint8 reason, string beneficiary );
modifier onlyOwnerOrOverride() {
// owner or any addresses listed in the overrides
// can perform token transfers while inactive
require(msg.sender == owner || allowedOverrideAddresses[msg.sender]);
_;
}
struct LOCIuser {
uint256 credits;
bool registered;
address wallet;
}
constructor( address _token, string _contactInformation ) public {
owner = msg.sender;
token = StandardToken(_token); // LOCIcoin address
contactInformation = _contactInformation;
}
function increaseCredits( string _id, uint256 _value, uint8 _reason, address _register ) public onlyOwnerOrOverride returns(uint256) {
LOCIuser storage user = users[_id];
if( !user.registered ) {
user.registered = true;
userKeys.push(_id);
userCount = userCount.add(1);
emit UserAdded(_id,now);
}
user.credits = user.credits.add(_value);
require( token.transferFrom( _register, address(this), _value ) );
emit CreditsAdjusted(_id, 1, _value, _reason, _register);
return user.credits;
}
function reduceCredits( string _id, uint256 _value, uint8 _reason, address _register ) public onlyOwnerOrOverride returns(uint256) {
LOCIuser storage user = users[_id];
require( user.registered );
// SafeMath.sub will throw if there is not enough balance.
user.credits = user.credits.sub(_value);
require( user.credits >= 0 );
require( token.transfer( _register, _value ) );
emit CreditsAdjusted(_id, 2, _value, _reason, _register);
return user.credits;
}
function buyCreditsAndSpend( string _id, uint256 _value, uint8 _reason, address _register, uint256 _spend ) public onlyOwnerOrOverride returns(uint256) {
increaseCredits(_id, _value, _reason, _register);
return reduceCredits(_id, _spend, _reason, _register );
}
function buyCreditsAndSpendAndRecover(string _id, uint256 _value, uint8 _reason, address _register, uint256 _spend, address _recover ) public onlyOwnerOrOverride returns(uint256) {
buyCreditsAndSpend(_id, _value, _reason, _register, _spend);
return reduceCredits(_id, getCreditsFor(_id), _reason, _recover);
}
function transferCreditsInternally( string _id, uint256 _value, uint8 _reason, string _beneficiary ) public onlyOwnerOrOverride returns(uint256) {
LOCIuser storage user = users[_id];
require( user.registered );
LOCIuser storage beneficiary = users[_beneficiary];
if( !beneficiary.registered ) {
beneficiary.registered = true;
userKeys.push(_beneficiary);
userCount = userCount.add(1);
emit UserAdded(_beneficiary,now);
}
require(_value <= user.credits);
user.credits = user.credits.sub(_value);
require( user.credits >= 0 );
beneficiary.credits = beneficiary.credits.add(_value);
require( beneficiary.credits >= _value );
emit CreditsAdjusted(_id, 2, _value, _reason, 0x0);
emit CreditsAdjusted(_beneficiary, 1, _value, _reason, 0x0);
emit CreditsTransferred(_id, _value, _reason, _beneficiary );
return user.credits;
}
function assignUserWallet( string _id, address _wallet ) public onlyOwnerOrOverride returns(uint256) {
LOCIuser storage user = users[_id];
require( user.registered );
user.wallet = _wallet;
return user.credits;
}
function withdrawUserSpecifiedFunds( string _id, uint256 _value, uint8 _reason ) public returns(uint256) {
LOCIuser storage user = users[_id];
require( user.registered, "user is not registered" );
require( user.wallet == msg.sender, "user.wallet is not msg.sender" );
user.credits = user.credits.sub(_value);
require( user.credits >= 0 );
require( token.transfer( user.wallet, _value ), "transfer failed" );
emit CreditsAdjusted(_id, 2, _value, _reason, user.wallet );
return user.credits;
}
function getUserWallet( string _id ) public constant returns(address) {
return users[_id].wallet;
}
function getTotalSupply() public constant returns(uint256) {
return token.balanceOf(address(this));
}
function getCreditsFor( string _id ) public constant returns(uint256) {
return users[_id].credits;
}
function getUserCount() public constant returns(uint256) {
return userCount;
}
function getUserKey(uint256 _index) public constant returns(string) {
require(_index <= userKeys.length-1);
return userKeys[_index];
}
function getCreditsAtIndex(uint256 _index) public constant returns(uint256) {
return getCreditsFor(getUserKey(_index));
}
// non-core functionality
function ownerSetOverride(address _address, bool enable) external onlyOwner {
allowedOverrideAddresses[_address] = enable;
}
function isAllowedOverrideAddress(address _addr) external constant returns (bool) {
return allowedOverrideAddresses[_addr];
}
// enable recovery of ether sent to this contract
function ownerTransferWei(address _beneficiary, uint256 _value) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
// if zero requested, send the entire amount, otherwise the amount requested
uint256 _amount = _value > 0 ? _value : address(this).balance;
_beneficiary.transfer(_amount);
}
// enable recovery of LOCIcoin sent to this contract
function ownerRecoverTokens(address _beneficiary) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
uint256 _tokensRemaining = token.balanceOf(address(this));
if (_tokensRemaining > 0) {
token.transfer(_beneficiary, _tokensRemaining);
}
}
// enable recovery of any other StandardToken sent to this contract
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return StandardToken(tokenAddress).transfer(owner, tokens);
}
} | enable recovery of ether sent to this contract if zero requested, send the entire amount, otherwise the amount requested | function ownerTransferWei(address _beneficiary, uint256 _value) external onlyOwner {
require(_beneficiary != 0x0);
require(_beneficiary != address(token));
uint256 _amount = _value > 0 ? _value : address(this).balance;
_beneficiary.transfer(_amount);
}
| 6,136,395 | [
1,
7589,
11044,
434,
225,
2437,
3271,
358,
333,
6835,
309,
3634,
3764,
16,
1366,
326,
7278,
3844,
16,
3541,
326,
3844,
3764,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
445,
3410,
5912,
3218,
77,
12,
2867,
389,
70,
4009,
74,
14463,
814,
16,
2254,
5034,
389,
1132,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
374,
92,
20,
1769,
203,
3639,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
1758,
12,
2316,
10019,
540,
203,
203,
3639,
2254,
5034,
389,
8949,
273,
389,
1132,
405,
374,
692,
389,
1132,
294,
1758,
12,
2211,
2934,
12296,
31,
203,
203,
3639,
389,
70,
4009,
74,
14463,
814,
18,
13866,
24899,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xE92df22c47562E171Df5EdaC071154fF1D9EA88e/sources/contracts/StandardToken.sol | * @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 override returns (bool) {
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 8,145,240 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
24899,
1132,
1648,
324,
26488,
63,
67,
2080,
19226,
203,
3639,
2583,
24899,
1132,
1648,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
19226,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
203,
3639,
324,
26488,
63,
67,
2080,
65,
273,
324,
26488,
63,
67,
2080,
8009,
1717,
24899,
1132,
1769,
203,
3639,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
65,
273,
2935,
63,
67,
2080,
6362,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
3626,
12279,
24899,
2080,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title It holds the storage variables related to ERC20DividendCheckpoint module
*/
contract ERC20DividendCheckpointStorage {
// Mapping to token address for each dividend
mapping (uint256 => address) public dividendTokens;
}
/**
* @title Holds the storage variable for the DividendCheckpoint modules (i.e ERC20, Ether)
* @dev abstract contract
*/
contract DividendCheckpointStorage {
// Address to which reclaimed dividends and withholding tax is sent
address public wallet;
uint256 public EXCLUDED_ADDRESS_LIMIT = 150;
bytes32 public constant DISTRIBUTE = "DISTRIBUTE";
bytes32 public constant MANAGE = "MANAGE";
bytes32 public constant CHECKPOINT = "CHECKPOINT";
struct Dividend {
uint256 checkpointId;
uint256 created; // Time at which the dividend was created
uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass
uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer -
// set to very high value to bypass
uint256 amount; // Dividend amount in WEI
uint256 claimedAmount; // Amount of dividend claimed so far
uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this)
bool reclaimed; // True if expiry has passed and issuer has reclaimed remaining dividend
uint256 totalWithheld;
uint256 totalWithheldWithdrawn;
mapping (address => bool) claimed; // List of addresses which have claimed dividend
mapping (address => bool) dividendExcluded; // List of addresses which cannot claim dividends
mapping (address => uint256) withheld; // Amount of tax withheld from claim
bytes32 name; // Name/title - used for identification
}
// List of all dividends
Dividend[] public dividends;
// List of addresses which cannot claim dividends
address[] public excluded;
// Mapping from address to withholding tax as a percentage * 10**16
mapping (address => uint256) public withholdingTax;
}
/**
* @title Proxy
* @dev Gives the possibility to delegate any call to a foreign implementation.
*/
contract Proxy {
/**
* @dev Tells the address of the implementation where every call will be delegated.
* @return address of the implementation to which it will be delegated
*/
function _implementation() internal view returns (address);
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
function _fallback() internal {
_delegate(_implementation());
}
/**
* @dev Fallback function allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
function _delegate(address implementation) internal {
/*solium-disable-next-line security/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) }
}
}
function () public payable {
_fallback();
}
}
/**
* @title OwnedProxy
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
*/
contract OwnedProxy is Proxy {
// Owner of the contract
address private __owner;
// Address of the current implementation
address internal __implementation;
/**
* @dev Event to show ownership has been transferred
* @param _previousOwner representing the address of the previous owner
* @param _newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address _previousOwner, address _newOwner);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier ifOwner() {
if (msg.sender == _owner()) {
_;
} else {
_fallback();
}
}
/**
* @dev the constructor sets the original owner of the contract to the sender account.
*/
constructor() public {
_setOwner(msg.sender);
}
/**
* @dev Tells the address of the owner
* @return the address of the owner
*/
function _owner() internal view returns (address) {
return __owner;
}
/**
* @dev Sets the address of the owner
*/
function _setOwner(address _newOwner) internal {
require(_newOwner != address(0), "Address should not be 0x");
__owner = _newOwner;
}
/**
* @notice Internal function to provide the address of the implementation contract
*/
function _implementation() internal view returns (address) {
return __implementation;
}
/**
* @dev Tells the address of the proxy owner
* @return the address of the proxy owner
*/
function proxyOwner() external ifOwner returns (address) {
return _owner();
}
/**
* @dev Tells the address of the current implementation
* @return address of the current implementation
*/
function implementation() external ifOwner returns (address) {
return _implementation();
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address _newOwner) external ifOwner {
require(_newOwner != address(0), "Address should not be 0x");
emit ProxyOwnershipTransferred(_owner(), _newOwner);
_setOwner(_newOwner);
}
}
/**
* @title Utility contract to allow pausing and unpausing of certain functions
*/
contract Pausable {
event Pause(uint256 _timestammp);
event Unpause(uint256 _timestamp);
bool public paused = false;
/**
* @notice Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused, "Contract is paused");
_;
}
/**
* @notice Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused, "Contract is not paused");
_;
}
/**
* @notice Called by the owner to pause, triggers stopped state
*/
function _pause() internal whenNotPaused {
paused = true;
/*solium-disable-next-line security/no-block-members*/
emit Pause(now);
}
/**
* @notice Called by the owner to unpause, returns to normal state
*/
function _unpause() internal whenPaused {
paused = false;
/*solium-disable-next-line security/no-block-members*/
emit Unpause(now);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function decreaseApproval(address _spender, uint _subtractedValue) external returns (bool);
function increaseApproval(address _spender, uint _addedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Storage for Module contract
* @notice Contract is abstract
*/
contract ModuleStorage {
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress) public {
securityToken = _securityToken;
factory = msg.sender;
polyToken = IERC20(_polyAddress);
}
address public factory;
address public securityToken;
bytes32 public constant FEE_ADMIN = "FEE_ADMIN";
IERC20 public polyToken;
}
/**
* @title Transfer Manager module for core transfer validation functionality
*/
contract ERC20DividendCheckpointProxy is ERC20DividendCheckpointStorage, DividendCheckpointStorage, ModuleStorage, Pausable, OwnedProxy {
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
* @param _implementation representing the address of the new implementation to be set
*/
constructor (address _securityToken, address _polyAddress, address _implementation)
public
ModuleStorage(_securityToken, _polyAddress)
{
require(
_implementation != address(0),
"Implementation address should not be 0x"
);
__implementation = _implementation;
}
}
/**
* @title Utility contract for reusable code
*/
library Util {
/**
* @notice Changes a string to upper case
* @param _base String to change
*/
function upper(string _base) internal pure returns (string) {
bytes memory _baseBytes = bytes(_base);
for (uint i = 0; i < _baseBytes.length; i++) {
bytes1 b1 = _baseBytes[i];
if (b1 >= 0x61 && b1 <= 0x7A) {
b1 = bytes1(uint8(b1)-32);
}
_baseBytes[i] = b1;
}
return string(_baseBytes);
}
/**
* @notice Changes the string into bytes32
* @param _source String that need to convert into bytes32
*/
/// Notice - Maximum Length for _source will be 32 chars otherwise returned bytes32 value will have lossy value.
function stringToBytes32(string memory _source) internal pure returns (bytes32) {
return bytesToBytes32(bytes(_source), 0);
}
/**
* @notice Changes bytes into bytes32
* @param _b Bytes that need to convert into bytes32
* @param _offset Offset from which to begin conversion
*/
/// Notice - Maximum length for _source will be 32 chars otherwise returned bytes32 value will have lossy value.
function bytesToBytes32(bytes _b, uint _offset) internal pure returns (bytes32) {
bytes32 result;
for (uint i = 0; i < _b.length; i++) {
result |= bytes32(_b[_offset + i] & 0xFF) >> (i * 8);
}
return result;
}
/**
* @notice Changes the bytes32 into string
* @param _source that need to convert into string
*/
function bytes32ToString(bytes32 _source) internal pure returns (string result) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(_source) * 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);
}
/**
* @notice Gets function signature from _data
* @param _data Passed data
* @return bytes4 sig
*/
function getSig(bytes _data) internal pure returns (bytes4 sig) {
uint len = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < len; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));
}
}
}
interface IBoot {
/**
* @notice This function returns the signature of configure function
* @return bytes4 Configure function signature
*/
function getInitFunction() external pure returns(bytes4);
}
/**
* @title Interface that every module factory contract should implement
*/
interface IModuleFactory {
event ChangeFactorySetupFee(uint256 _oldSetupCost, uint256 _newSetupCost, address _moduleFactory);
event ChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event ChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event GenerateModuleFromFactory(
address _module,
bytes32 indexed _moduleName,
address indexed _moduleFactory,
address _creator,
uint256 _setupCost,
uint256 _timestamp
);
event ChangeSTVersionBound(string _boundType, uint8 _major, uint8 _minor, uint8 _patch);
//Should create an instance of the Module, or throw
function deploy(bytes _data) external returns(address);
/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[]);
/**
* @notice Get the name of the Module
*/
function getName() external view returns(bytes32);
/**
* @notice Returns the instructions associated with the module
*/
function getInstructions() external view returns (string);
/**
* @notice Get the tags related to the module factory
*/
function getTags() external view returns (bytes32[]);
/**
* @notice Used to change the setup fee
* @param _newSetupCost New setup fee
*/
function changeFactorySetupFee(uint256 _newSetupCost) external;
/**
* @notice Used to change the usage fee
* @param _newUsageCost New usage fee
*/
function changeFactoryUsageFee(uint256 _newUsageCost) external;
/**
* @notice Used to change the subscription fee
* @param _newSubscriptionCost New subscription fee
*/
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) external;
/**
* @notice Function use to change the lower and upper bound of the compatible version st
* @param _boundType Type of bound
* @param _newVersion New version array
*/
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external;
/**
* @notice Get the setup cost of the module
*/
function getSetupCost() external view returns (uint256);
/**
* @notice Used to get the lower bound
* @return Lower bound
*/
function getLowerSTVersionBounds() external view returns(uint8[]);
/**
* @notice Used to get the upper bound
* @return Upper bound
*/
function getUpperSTVersionBounds() external view returns(uint8[]);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Helper library use to compare or validate the semantic versions
*/
library VersionUtils {
/**
* @notice This function is used to validate the version submitted
* @param _current Array holds the present version of ST
* @param _new Array holds the latest version of the ST
* @return bool
*/
function isValidVersion(uint8[] _current, uint8[] _new) internal pure returns(bool) {
bool[] memory _temp = new bool[](_current.length);
uint8 counter = 0;
for (uint8 i = 0; i < _current.length; i++) {
if (_current[i] < _new[i])
_temp[i] = true;
else
_temp[i] = false;
}
for (i = 0; i < _current.length; i++) {
if (i == 0) {
if (_current[i] <= _new[i])
if(_temp[0]) {
counter = counter + 3;
break;
} else
counter++;
else
return false;
} else {
if (_temp[i-1])
counter++;
else if (_current[i] <= _new[i])
counter++;
else
return false;
}
}
if (counter == _current.length)
return true;
}
/**
* @notice Used to compare the lower bound with the latest version
* @param _version1 Array holds the lower bound of the version
* @param _version2 Array holds the latest version of the ST
* @return bool
*/
function compareLowerBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version2[i] > _version1[i])
return true;
else if (_version2[i] < _version1[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
/**
* @notice Used to compare the upper bound with the latest version
* @param _version1 Array holds the upper bound of the version
* @param _version2 Array holds the latest version of the ST
* @return bool
*/
function compareUpperBound(uint8[] _version1, uint8[] _version2) internal pure returns(bool) {
require(_version1.length == _version2.length, "Input length mismatch");
uint counter = 0;
for (uint8 j = 0; j < _version1.length; j++) {
if (_version1[j] == 0)
counter ++;
}
if (counter != _version1.length) {
counter = 0;
for (uint8 i = 0; i < _version1.length; i++) {
if (_version1[i] > _version2[i])
return true;
else if (_version1[i] < _version2[i])
return false;
else
counter++;
}
if (counter == _version1.length - 1)
return true;
else
return false;
} else
return true;
}
/**
* @notice Used to pack the uint8[] array data into uint24 value
* @param _major Major version
* @param _minor Minor version
* @param _patch Patch version
*/
function pack(uint8 _major, uint8 _minor, uint8 _patch) internal pure returns(uint24) {
return (uint24(_major) << 16) | (uint24(_minor) << 8) | uint24(_patch);
}
/**
* @notice Used to convert packed data into uint8 array
* @param _packedVersion Packed data
*/
function unpack(uint24 _packedVersion) internal pure returns (uint8[]) {
uint8[] memory _unpackVersion = new uint8[](3);
_unpackVersion[0] = uint8(_packedVersion >> 16);
_unpackVersion[1] = uint8(_packedVersion >> 8);
_unpackVersion[2] = uint8(_packedVersion);
return _unpackVersion;
}
}
/**
* @title Interface that any module factory contract should implement
* @notice Contract is abstract
*/
contract ModuleFactory is IModuleFactory, Ownable {
IERC20 public polyToken;
uint256 public usageCost;
uint256 public monthlySubscriptionCost;
uint256 public setupCost;
string public description;
string public version;
bytes32 public name;
string public title;
// @notice Allow only two variables to be stored
// 1. lowerBound
// 2. upperBound
// @dev (0.0.0 will act as the wildcard)
// @dev uint24 consists packed value of uint8 _major, uint8 _minor, uint8 _patch
mapping(string => uint24) compatibleSTVersionRange;
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public {
polyToken = IERC20(_polyAddress);
setupCost = _setupCost;
usageCost = _usageCost;
monthlySubscriptionCost = _subscriptionCost;
}
/**
* @notice Used to change the fee of the setup cost
* @param _newSetupCost new setup cost
*/
function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner {
emit ChangeFactorySetupFee(setupCost, _newSetupCost, address(this));
setupCost = _newSetupCost;
}
/**
* @notice Used to change the fee of the usage cost
* @param _newUsageCost new usage cost
*/
function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner {
emit ChangeFactoryUsageFee(usageCost, _newUsageCost, address(this));
usageCost = _newUsageCost;
}
/**
* @notice Used to change the fee of the subscription cost
* @param _newSubscriptionCost new subscription cost
*/
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit ChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
/**
* @notice Updates the title of the ModuleFactory
* @param _newTitle New Title that will replace the old one.
*/
function changeTitle(string _newTitle) public onlyOwner {
require(bytes(_newTitle).length > 0, "Invalid title");
title = _newTitle;
}
/**
* @notice Updates the description of the ModuleFactory
* @param _newDesc New description that will replace the old one.
*/
function changeDescription(string _newDesc) public onlyOwner {
require(bytes(_newDesc).length > 0, "Invalid description");
description = _newDesc;
}
/**
* @notice Updates the name of the ModuleFactory
* @param _newName New name that will replace the old one.
*/
function changeName(bytes32 _newName) public onlyOwner {
require(_newName != bytes32(0),"Invalid name");
name = _newName;
}
/**
* @notice Updates the version of the ModuleFactory
* @param _newVersion New name that will replace the old one.
*/
function changeVersion(string _newVersion) public onlyOwner {
require(bytes(_newVersion).length > 0, "Invalid version");
version = _newVersion;
}
/**
* @notice Function use to change the lower and upper bound of the compatible version st
* @param _boundType Type of bound
* @param _newVersion new version array
*/
function changeSTVersionBounds(string _boundType, uint8[] _newVersion) external onlyOwner {
require(
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("lowerBound")) ||
keccak256(abi.encodePacked(_boundType)) == keccak256(abi.encodePacked("upperBound")),
"Must be a valid bound type"
);
require(_newVersion.length == 3);
if (compatibleSTVersionRange[_boundType] != uint24(0)) {
uint8[] memory _currentVersion = VersionUtils.unpack(compatibleSTVersionRange[_boundType]);
require(VersionUtils.isValidVersion(_currentVersion, _newVersion), "Failed because of in-valid version");
}
compatibleSTVersionRange[_boundType] = VersionUtils.pack(_newVersion[0], _newVersion[1], _newVersion[2]);
emit ChangeSTVersionBound(_boundType, _newVersion[0], _newVersion[1], _newVersion[2]);
}
/**
* @notice Used to get the lower bound
* @return lower bound
*/
function getLowerSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["lowerBound"]);
}
/**
* @notice Used to get the upper bound
* @return upper bound
*/
function getUpperSTVersionBounds() external view returns(uint8[]) {
return VersionUtils.unpack(compatibleSTVersionRange["upperBound"]);
}
/**
* @notice Get the setup cost of the module
*/
function getSetupCost() external view returns (uint256) {
return setupCost;
}
/**
* @notice Get the name of the Module
*/
function getName() public view returns(bytes32) {
return name;
}
}
/**
* @title Factory for deploying ERC20DividendCheckpoint module
*/
contract ERC20DividendCheckpointFactory is ModuleFactory {
address public logicContract;
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
* @param _setupCost Setup cost of the module
* @param _usageCost Usage cost of the module
* @param _subscriptionCost Subscription cost of the module
* @param _logicContract Contract address that contains the logic related to `description`
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost, address _logicContract) public
ModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost)
{
require(_logicContract != address(0), "Invalid logic contract");
version = "2.1.1";
name = "ERC20DividendCheckpoint";
title = "ERC20 Dividend Checkpoint";
description = "Create ERC20 dividends for token holders at a specific checkpoint";
compatibleSTVersionRange["lowerBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
compatibleSTVersionRange["upperBound"] = VersionUtils.pack(uint8(0), uint8(0), uint8(0));
logicContract = _logicContract;
}
/**
* @notice Used to launch the Module with the help of factory
* @return Address Contract address of the Module
*/
function deploy(bytes _data) external returns(address) {
if (setupCost > 0)
require(polyToken.transferFrom(msg.sender, owner, setupCost), "insufficent allowance");
address erc20DividendCheckpoint = new ERC20DividendCheckpointProxy(msg.sender, address(polyToken), logicContract);
//Checks that _data is valid (not calling anything it shouldn't)
require(Util.getSig(_data) == IBoot(erc20DividendCheckpoint).getInitFunction(), "Invalid data");
/*solium-disable-next-line security/no-low-level-calls*/
require(erc20DividendCheckpoint.call(_data), "Unsuccessfull call");
/*solium-disable-next-line security/no-block-members*/
emit GenerateModuleFromFactory(erc20DividendCheckpoint, getName(), address(this), msg.sender, setupCost, now);
return erc20DividendCheckpoint;
}
/**
* @notice Type of the Module factory
*/
function getTypes() external view returns(uint8[]) {
uint8[] memory res = new uint8[](1);
res[0] = 4;
return res;
}
/**
* @notice Returns the instructions associated with the module
*/
function getInstructions() external view returns(string) {
return "Create ERC20 dividend to be paid out to token holders based on their balances at dividend creation time";
}
/**
* @notice Get the tags related to the module factory
*/
function getTags() external view returns(bytes32[]) {
bytes32[] memory availableTags = new bytes32[](3);
availableTags[0] = "ERC20";
availableTags[1] = "Dividend";
availableTags[2] = "Checkpoint";
return availableTags;
}
} | * @dev Sets the address of the owner/ | function _setOwner(address _newOwner) internal {
require(_newOwner != address(0), "Address should not be 0x");
__owner = _newOwner;
}
| 926,187 | [
1,
2785,
326,
1758,
434,
326,
3410,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
542,
5541,
12,
2867,
389,
2704,
5541,
13,
2713,
288,
203,
3639,
2583,
24899,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
1887,
1410,
486,
506,
374,
92,
8863,
203,
3639,
1001,
8443,
273,
389,
2704,
5541,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
pragma abicoder v2;
import './UserStorage.sol';
import './TweetStorage.sol';
contract SolidTwitter is OwnedObject {
address public userStorageAddr;
address public tweetStorageAddr;
// Aware of the actual data, so that the storage contract can be updated easily
address public userDataAddr;
address public tweetDataAddr;
modifier storageBinded() {
require(userStorageAddr != address(0));
require(tweetStorageAddr != address(0));
require(userDataAddr != address(0));
require(tweetDataAddr != address(0));
_;
}
modifier validUser(address _addr) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(_addr);
require(userId != 0);
_;
}
function bindUserStorage(address _addr) public onlyOwner {
userStorageAddr = _addr;
}
function bindTweetStorage(address _addr) public onlyOwner {
tweetStorageAddr = _addr;
}
function bindUserData(address _addr) public onlyOwner {
userDataAddr = _addr;
}
function bindTweetData(address _addr) public onlyOwner {
tweetDataAddr = _addr;
}
function createUser(bytes32 _username, string memory _publicName) public storageBinded returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.createUserProfile(msg.sender, _username, _publicName, "");
}
function getUserId(address _addr) public storageBinded view returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserId(_addr);
}
function getUserAddress(bytes32 _username) public storageBinded view returns(address _addr) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserAddress(_username);
}
function getUserTweetNum(uint _userId) public storageBinded view returns(uint _tweetNum) {
UserStorage userStorage = UserStorage(userStorageAddr);
_tweetNum = userStorage.getUserTweetNum(_userId);
}
function getUserProfile(uint _userId) public storageBinded view returns(UserProfile memory) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserProfile(_userId);
}
function addSubscription(uint _id, uint _subId) public storageBinded {
UserStorage userStorage = UserStorage(userStorageAddr);
userStorage.addUserSubscription(_id, _subId);
}
function removeSubscription(uint _id, uint _subId) public storageBinded {
UserStorage userStorage = UserStorage(userStorageAddr);
userStorage.removeUserSubscription(_id, _subId);
}
function getSubscription(uint _id, uint _index) public storageBinded view returns(uint _subId) {
UserStorage userStorage = UserStorage(userStorageAddr);
_subId = userStorage.getUserSubscription(_id, _index);
}
function getSubscriptionCount(uint _id) public storageBinded view returns(uint _count) {
UserStorage userStorage = UserStorage(userStorageAddr);
_count = userStorage.getUserSubscriptionCount(_id);
}
function getSubscriptionBatch(uint _id, uint _offset) public storageBinded view returns(uint[] memory) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserSubscriptionBatch(_id, _offset);
}
function changePublicName(string memory _newName) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.updatePublicName(userId, _newName);
}
function changeProfilePicture(string memory _newPicture) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.setUserProfilePicture(userId, _newPicture);
}
function updateBio(string memory _newBio) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.updateBio(userId, _newBio);
}
function tweet(string memory _text) public storageBinded validUser(msg.sender) returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
// Let storage handle the rest
_id = tweetStorage.tweet(userId, userStorage.getUserTweetNum(userId), _text);
userStorage.incrementUserTweetNum(userId);
}
function reply(uint _tweetId, string memory _text) public storageBinded validUser(msg.sender) returns(uint _id) {
// Don't allow empty replies
require((bytes(_text).length > 0));
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
_id = tweetStorage.reply(userId, userStorage.getUserTweetNum(userId), _tweetId, _text);
userStorage.incrementUserTweetNum(userId);
}
// We treat ReTweets as empty replies without adding this tweet as a reply and incrementing tweet retweet count
function retweet(uint _originalTweetId) public storageBinded validUser(msg.sender) returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
// Can't retweet own tweet
TweetContent memory originalTweet = tweetStorage.getTweet(_originalTweetId);
require(originalTweet.authorId != userId);
_id = tweetStorage.retweet(userId, userStorage.getUserTweetNum(userId), _originalTweetId);
userStorage.incrementUserTweetNum(userId);
}
function getTweet(uint _tweetId) public storageBinded view returns(TweetContent memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
return tweetStorage.getTweet(_tweetId);
}
function getTweet(uint _userId, uint _tweetNum) public storageBinded view returns(TweetContent memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
uint tweetId = uint(keccak256(abi.encodePacked(_userId, _tweetNum)));
return tweetStorage.getTweet(tweetId);
}
function getTweetBatch(uint _userId, uint _startNum, uint _count) public storageBinded view returns(TweetContent[] memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
return tweetStorage.getTweetBatch(_startNum, _userId, _count);
}
} | Aware of the actual data, so that the storage contract can be updated easily | contract SolidTwitter is OwnedObject {
address public userStorageAddr;
address public tweetStorageAddr;
address public userDataAddr;
address public tweetDataAddr;
pragma solidity >=0.7.0 <0.9.0;
modifier storageBinded() {
require(userStorageAddr != address(0));
require(tweetStorageAddr != address(0));
require(userDataAddr != address(0));
require(tweetDataAddr != address(0));
_;
}
modifier validUser(address _addr) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(_addr);
require(userId != 0);
_;
}
function bindUserStorage(address _addr) public onlyOwner {
userStorageAddr = _addr;
}
function bindTweetStorage(address _addr) public onlyOwner {
tweetStorageAddr = _addr;
}
function bindUserData(address _addr) public onlyOwner {
userDataAddr = _addr;
}
function bindTweetData(address _addr) public onlyOwner {
tweetDataAddr = _addr;
}
function createUser(bytes32 _username, string memory _publicName) public storageBinded returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.createUserProfile(msg.sender, _username, _publicName, "");
}
function getUserId(address _addr) public storageBinded view returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserId(_addr);
}
function getUserAddress(bytes32 _username) public storageBinded view returns(address _addr) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserAddress(_username);
}
function getUserTweetNum(uint _userId) public storageBinded view returns(uint _tweetNum) {
UserStorage userStorage = UserStorage(userStorageAddr);
_tweetNum = userStorage.getUserTweetNum(_userId);
}
function getUserProfile(uint _userId) public storageBinded view returns(UserProfile memory) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserProfile(_userId);
}
function addSubscription(uint _id, uint _subId) public storageBinded {
UserStorage userStorage = UserStorage(userStorageAddr);
userStorage.addUserSubscription(_id, _subId);
}
function removeSubscription(uint _id, uint _subId) public storageBinded {
UserStorage userStorage = UserStorage(userStorageAddr);
userStorage.removeUserSubscription(_id, _subId);
}
function getSubscription(uint _id, uint _index) public storageBinded view returns(uint _subId) {
UserStorage userStorage = UserStorage(userStorageAddr);
_subId = userStorage.getUserSubscription(_id, _index);
}
function getSubscriptionCount(uint _id) public storageBinded view returns(uint _count) {
UserStorage userStorage = UserStorage(userStorageAddr);
_count = userStorage.getUserSubscriptionCount(_id);
}
function getSubscriptionBatch(uint _id, uint _offset) public storageBinded view returns(uint[] memory) {
UserStorage userStorage = UserStorage(userStorageAddr);
return userStorage.getUserSubscriptionBatch(_id, _offset);
}
function changePublicName(string memory _newName) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.updatePublicName(userId, _newName);
}
function changeProfilePicture(string memory _newPicture) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.setUserProfilePicture(userId, _newPicture);
}
function updateBio(string memory _newBio) public storageBinded validUser(msg.sender) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
userStorage.updateBio(userId, _newBio);
}
function tweet(string memory _text) public storageBinded validUser(msg.sender) returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
_id = tweetStorage.tweet(userId, userStorage.getUserTweetNum(userId), _text);
userStorage.incrementUserTweetNum(userId);
}
function reply(uint _tweetId, string memory _text) public storageBinded validUser(msg.sender) returns(uint _id) {
require((bytes(_text).length > 0));
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
_id = tweetStorage.reply(userId, userStorage.getUserTweetNum(userId), _tweetId, _text);
userStorage.incrementUserTweetNum(userId);
}
function retweet(uint _originalTweetId) public storageBinded validUser(msg.sender) returns(uint _id) {
UserStorage userStorage = UserStorage(userStorageAddr);
uint userId = userStorage.getUserId(msg.sender);
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
TweetContent memory originalTweet = tweetStorage.getTweet(_originalTweetId);
require(originalTweet.authorId != userId);
_id = tweetStorage.retweet(userId, userStorage.getUserTweetNum(userId), _originalTweetId);
userStorage.incrementUserTweetNum(userId);
}
function getTweet(uint _tweetId) public storageBinded view returns(TweetContent memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
return tweetStorage.getTweet(_tweetId);
}
function getTweet(uint _userId, uint _tweetNum) public storageBinded view returns(TweetContent memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
uint tweetId = uint(keccak256(abi.encodePacked(_userId, _tweetNum)));
return tweetStorage.getTweet(tweetId);
}
function getTweetBatch(uint _userId, uint _startNum, uint _count) public storageBinded view returns(TweetContent[] memory) {
TweetStorage tweetStorage = TweetStorage(tweetStorageAddr);
return tweetStorage.getTweetBatch(_startNum, _userId, _count);
}
} | 7,305,792 | [
1,
10155,
434,
326,
3214,
501,
16,
1427,
716,
326,
2502,
6835,
848,
506,
3526,
17997,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
348,
7953,
23539,
6132,
353,
14223,
11748,
921,
225,
288,
203,
377,
203,
565,
1758,
1071,
729,
3245,
3178,
31,
203,
565,
1758,
1071,
18320,
3245,
3178,
31,
203,
203,
565,
1758,
1071,
13530,
3178,
31,
203,
565,
1758,
1071,
18320,
751,
3178,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
565,
9606,
2502,
9913,
785,
1435,
288,
203,
3639,
2583,
12,
1355,
3245,
3178,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
88,
18028,
3245,
3178,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
1355,
751,
3178,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
88,
18028,
751,
3178,
480,
1758,
12,
20,
10019,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
9606,
923,
1299,
12,
2867,
389,
4793,
13,
288,
203,
3639,
2177,
3245,
729,
3245,
273,
2177,
3245,
12,
1355,
3245,
3178,
1769,
7010,
3639,
2254,
6249,
273,
729,
3245,
18,
588,
10502,
24899,
4793,
1769,
203,
3639,
2583,
12,
18991,
480,
374,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1993,
1299,
3245,
12,
2867,
389,
4793,
13,
1071,
1338,
5541,
288,
203,
3639,
729,
3245,
3178,
273,
389,
4793,
31,
203,
565,
289,
203,
203,
565,
445,
1993,
56,
18028,
3245,
12,
2867,
389,
4793,
13,
1071,
1338,
5541,
288,
203,
3639,
18320,
3245,
3178,
273,
389,
4793,
31,
203,
565,
289,
203,
203,
565,
445,
1993,
19265,
12,
2867,
389,
4793,
13,
1071,
1338,
5541,
2
] |
pragma solidity 0.4.24;
library ECRecovery {
/**
* @dev Recover signer address from a message by using his signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = 0x0;
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract RedemptionCertificate is Claimable {
using ECRecovery for bytes32;
/// @dev A set of addresses that are approved to sign on behalf of this contract
mapping(address => bool) public signers;
/// @dev The nonce associated with each hash(accountId). In this case, the account is an external
/// concept that does not correspond to an Ethereum address. Therefore, the hash of the accountId
/// is used
mapping(bytes32 => uint256) public nonces;
address public token;
address public tokenHolder;
event TokenHolderChanged(address oldTokenHolder, address newTokenHolder);
event CertificateRedeemed(string accountId, uint256 amount, address recipient);
event SignerAdded(address signer);
event SignerRemoved(address signer);
constructor(address _token, address _tokenHolder)
public
{
token = _token;
tokenHolder = _tokenHolder;
}
/**
* @dev ensures that the hash was signed by a valid signer. Also increments the associated
* account nonce to ensure that the same hash/signature cannot be used again
*/
modifier onlyValidSignatureOnce(string accountId, bytes32 hash, bytes signature) {
address signedBy = hash.recover(signature);
require(signers[signedBy]);
_;
nonces[hashAccountId(accountId)]++;
}
/**
* @dev Attempts to withdraw tokens from this contract, using the signature as proof
* that the caller is entitled to the specified amount.
*/
function withdraw(string accountId, uint256 amount, address recipient, bytes signature)
onlyValidSignatureOnce(
accountId,
generateWithdrawalHash(accountId, amount, recipient),
signature)
public
returns (bool)
{
require(ERC20(token).transferFrom(tokenHolder, recipient, amount));
emit CertificateRedeemed(accountId, amount, recipient);
return true;
}
/// Helper Methods
/**
* @dev Generates the hash of the message that needs to be signed by an approved signer.
* The nonce is read directly from the contract's state.
*/
function generateWithdrawalHash(string accountId, uint256 amount, address recipient)
view
public
returns (bytes32)
{
bytes32 accountHash = hashAccountId(accountId);
bytes memory message = abi.encodePacked(address(this), recipient, amount, nonces[accountHash]);
bytes32 messageHash = keccak256(message);
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash));
}
/**
* @dev converts and accoutId to a bytes32
*/
function hashAccountId(string accountId)
pure
internal
returns (bytes32)
{
return keccak256(abi.encodePacked(accountId));
}
/// Admin Methods
function updateTokenHolder(address newTokenHolder)
onlyOwner
external
{
address oldTokenHolder = tokenHolder;
tokenHolder = newTokenHolder;
emit TokenHolderChanged(oldTokenHolder, newTokenHolder);
}
function addSigner(address signer)
onlyOwner
external
{
signers[signer] = true;
emit SignerAdded(signer);
}
function removeSigner(address signer)
onlyOwner
external
{
signers[signer] = false;
emit SignerRemoved(signer);
}
} | @dev A set of addresses that are approved to sign on behalf of this contract @dev The nonce associated with each hash(accountId). In this case, the account is an external concept that does not correspond to an Ethereum address. Therefore, the hash of the accountId is used | {
token = _token;
tokenHolder = _tokenHolder;
}
| 7,878,347 | [
1,
37,
444,
434,
6138,
716,
854,
20412,
358,
1573,
603,
12433,
6186,
434,
333,
6835,
225,
1021,
7448,
3627,
598,
1517,
1651,
12,
25701,
2934,
225,
657,
333,
648,
16,
326,
2236,
353,
392,
3903,
12402,
716,
1552,
486,
4325,
358,
392,
512,
18664,
379,
1758,
18,
225,
17189,
16,
326,
1651,
434,
326,
17398,
353,
1399,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
1147,
273,
389,
2316,
31,
203,
3639,
1147,
6064,
273,
389,
2316,
6064,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x2f95A41613a05a50dF71E296f963AB3C2B9Ea7fC/sources/contracts/CrowdFunding.sol | Goerli ETH / USD Address https:docs.chain.link/docs/ethereum-addresses/ ETH/USD rate in 18 digit or (Both will do the same thing) return uint256(answer * 1e10); 1* 10 ** 10 == 10000000000 | function getPrice() internal view returns (uint256) {
AggregatorV3Interface priceFeed = AggregatorV3Interface(
0xD4a33860578De61DBAbDc8BFdb98FD742fA7028e
);
(, int256 answer, , , ) = priceFeed.latestRoundData();
return uint256(answer * 10000000000);
}
| 1,932,344 | [
1,
5741,
264,
549,
512,
2455,
342,
587,
9903,
5267,
2333,
30,
8532,
18,
5639,
18,
1232,
19,
8532,
19,
546,
822,
379,
17,
13277,
19,
512,
2455,
19,
3378,
40,
4993,
316,
6549,
8035,
578,
261,
20240,
903,
741,
326,
1967,
7757,
13,
327,
2254,
5034,
12,
13490,
225,
404,
73,
2163,
1769,
225,
404,
1728,
225,
1728,
422,
2130,
12648,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
915,
25930,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
10594,
639,
58,
23,
1358,
6205,
8141,
273,
10594,
639,
58,
23,
1358,
12,
203,
5411,
374,
17593,
24,
69,
3707,
28,
4848,
25,
8285,
758,
9498,
2290,
5895,
40,
71,
28,
15259,
1966,
10689,
16894,
5608,
22,
29534,
27,
3103,
28,
73,
203,
3639,
11272,
203,
3639,
261,
16,
509,
5034,
5803,
16,
269,
269,
262,
273,
6205,
8141,
18,
13550,
11066,
751,
5621,
203,
3639,
327,
2254,
5034,
12,
13490,
380,
2130,
12648,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-08-29
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
/**
* @dev Interface for discreet in addition to the standard ERC721 interface.
*/
interface discreetNFTInterface {
/**
* @dev Mint token with the supplied tokenId if it is currently available.
*/
function mint(uint256 tokenId) external;
/**
* @dev Mint token with the supplied tokenId if it is currently available to
* another address.
*/
function mint(address to, uint256 tokenId) external;
/**
* @dev Burn token with the supplied tokenId if it is owned, approved or
* reclaimable. Tokens become reclaimable after ~4 million blocks without a
* mint or transfer.
*/
function burn(uint256 tokenId) external;
/**
* @dev Check the current block number at which a given token will become
* reclaimable.
*/
function reclaimableThreshold(uint256 tokenId) external view returns (uint256);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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);
}
interface IENSReverseRegistrar {
function claim(address owner) external returns (bytes32 node);
function setName(string calldata name) external returns (bytes32 node);
}
/**
* @dev Implementation of the {IERC165} interface.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @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 ERC165, IERC721, IERC721Metadata {
// Token name
bytes14 private immutable _name;
// Token symbol
bytes13 private immutable _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(bytes14 name_, bytes13 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() external view virtual override returns (string memory) {
return string(abi.encodePacked(_name));
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() external view virtual override returns (string memory) {
return string(abi.encodePacked(_symbol));
}
/**
* @dev NOTE: standard functionality overridden.
*/
function tokenURI(uint256 tokenId) external view virtual override returns (string memory) {}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) external virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) external virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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 {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, ""),
"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) {
uint256 size;
assembly { size := extcodesize(to) }
if (size > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @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 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) external 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) external 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();
}
}
/**
* @dev extra-discreet
* @author 0age
*/
contract extraDiscreetNFT is discreetNFTInterface, ERC721, ERC721Enumerable {
// Map tokenIds to block numbers past which they are burnable by any caller.
mapping(uint256 => uint256) private _reclaimableThreshold;
// Map transaction submitters to the block number of their last token mint.
mapping(address => uint256) private _lastTokenMinted;
// Fixed base64-encoded SVG fragments used across all images.
bytes32 private constant h0 = 'data:image/svg+xml;base64,PD94bW';
bytes32 private constant h1 = 'wgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz';
bytes32 private constant h2 = '0iVVRGLTgiPz48c3ZnIHZpZXdCb3g9Ij';
bytes32 private constant h3 = 'AgMCA1MDAgNTAwIiB4bWxucz0iaHR0cD';
bytes32 private constant h4 = 'ovL3d3dy53My5vcmcvMjAwMC9zdmciIH';
bytes32 private constant h5 = 'N0eWxlPSJiYWNrZ3JvdW5kLWNvbG9yOi';
bytes4 private constant m0 = 'iPjx';
bytes10 private constant m1 = 'BmaWxsPSIj';
bytes16 private constant f0 = 'IiAvPjwvc3ZnPg==';
address public constant discreet = 0x3c77065B584D4Af705B3E38CC35D336b081E4948;
address private immutable _admin;
uint256 private immutable _deployedAt;
mapping(address => bool) private _hasMintedAnOutOfRangeToken;
/**
* @dev Deploy discreet as an ERC721 NFT.
*/
constructor() ERC721("extra-discreet", "EXTRADISCREET") {
// Set up ENS reverse registrar.
IENSReverseRegistrar _ensReverseRegistrar = IENSReverseRegistrar(
0x084b1c3C81545d370f3634392De611CaaBFf8148
);
_ensReverseRegistrar.claim(msg.sender);
_ensReverseRegistrar.setName("extra.discreet.eth");
_admin = tx.origin;
_deployedAt = block.number;
}
/**
* @dev Throttle minting to once a block and reset the reclamation threshold
* whenever a new token is minted or transferred.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721, ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
// If minting: ensure it's the only one from this tx origin in the block.
if (from == address(0)) {
require(
block.number > _lastTokenMinted[tx.origin],
"extra-discreet: cannot mint multiple tokens per block from a single origin"
);
_lastTokenMinted[tx.origin] = block.number;
}
// If not burning: reset tokenId's reclaimable threshold block number.
if (to != address(0)) {
_reclaimableThreshold[tokenId] = block.number + 0x400000;
}
}
/**
* @dev Mint a given discreet NFT if it is currently available.
*/
function mint(uint256 tokenId) external override {
require(tokenId < 0x120, "extra-discreet: cannot mint out-of-range token");
require(
msg.sender == _admin || block.number > _deployedAt + 0x10000,
"extra-discreet: only admin can mint directly for initial period"
);
_safeMint(msg.sender, tokenId);
}
/**
* @dev Mint a given NFT if it is currently available to a given address.
*/
function mint(address to, uint256 tokenId) external override {
require(tokenId < 0x120, "extra-discreet: cannot mint out-of-range token");
require(
msg.sender == _admin || block.number > _deployedAt + 0x10000,
"extra-discreet: only admin can mint directly for initial period"
);
_safeMint(to, tokenId);
}
/**
* @dev Mint a given NFT if it is currently available to a given address.
*/
function mintFromOutOfRangeDiscreet(uint256 oldDiscreetTokenId, uint256 newExtraDiscreetTokenId) external {
require(
newExtraDiscreetTokenId < 0x120,
"extra-discreet: cannot mint out-of-range token"
);
// old token needs to be out of range
require(
oldDiscreetTokenId >= 0x240,
"extra-discreet: cannot mint using in-range discreet token"
);
// old token needs to be owned by caller
address oldOwner = IERC721(discreet).ownerOf(oldDiscreetTokenId);
require(
oldOwner == msg.sender,
"extra-discreet: cannot mint using unowned discreet token"
);
// token needs to be "old" (i.e. hasn't been minted or transferred since
// deploying this contract)
uint256 oldReclaimableThreshold = discreetNFTInterface(discreet).reclaimableThreshold(oldDiscreetTokenId);
uint256 lastMoved = oldReclaimableThreshold - 0x400000;
require(
lastMoved < _deployedAt,
"extra-discreet: cannot mint using out-of-range discreet token that has moved since deployment of this contract"
);
// Only one token can be minted per caller using this method
require(
!_hasMintedAnOutOfRangeToken[msg.sender],
"extra-discreet: can only mint using out-of-range discreet token once per caller"
);
_hasMintedAnOutOfRangeToken[msg.sender] = true;
_safeMint(msg.sender, newExtraDiscreetTokenId);
}
/**
* @dev Burn a given discreet NFT if it is owned, approved or reclaimable.
* Tokens become reclaimable after ~4 million blocks without a transfer.
*/
function burn(uint256 tokenId) external override {
// Only enforce check if tokenId has not reached reclaimable threshold.
if (_reclaimableThreshold[tokenId] < block.number) {
require(
_isApprovedOrOwner(msg.sender, tokenId),
"extra-discreet: caller is not owner nor approved"
);
}
_burn(tokenId);
}
/**
* @dev Check the current block number at which the given token will become
* reclaimable.
*/
function reclaimableThreshold(uint256 tokenId) external view override returns (uint256) {
return _reclaimableThreshold[tokenId];
}
/**
* @dev Derive and return a discreet tokenURI formatted as a data URI.
*/
function tokenURI(uint256 tokenId) external pure virtual override returns (string memory) {
require(tokenId < 0x120, "extra-discreet: URI query for out-of-range token");
// Nine base64-encoded SVG fragments for background colors.
bytes9[9] memory c0 = [
bytes9('MwMDAwMDA'),
'M2OWZmMzc',
'NmZjM3Njk',
'MzNzY5ZmY',
'NmZmZmOTA',
'M5MGZmZmY',
'NmZjkwZmY',
'NmZmZmZmY',
'M4MDgwODA'
];
// Four base64-encoded SVG fragments for primary shapes.
string[4] memory s0 = [
'wb2x5Z29uIHBvaW50cz0iNDAwLDEwMCA0MDAsNDAwIDEwMCw0MDAiIC',
'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsNDAwIDEwMCwxMDAiIC',
'wb2x5Z29uIHBvaW50cz0iMTAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC',
'wb2x5Z29uIHBvaW50cz0iNDAwLDQwMCA0MDAsMTAwIDEwMCwxMDAiIC'
];
// Nine base64-encoded SVG fragments for primary colors.
bytes8[9] memory c1 = [
bytes8('NjlmZjM3'),
'ZmYzNzY5',
'Mzc2OWZm',
'ZmZmZjkw',
'OTBmZmZm',
'ZmY5MGZm',
'ZmZmZmZm',
'ODA4MDgw',
'MDAwMDAw'
];
// Construct a discrete tokenURI from a unique combination of the above.
uint256 c0i = (tokenId % 72) / 8;
uint256 s0i = tokenId / 72;
uint256 c1i = (tokenId % 8 + (tokenId / 8)) % 9;
return string(
abi.encodePacked(
h0, h1, h2, h3, h4, h5, c0[c0i], m0, s0[s0i], m1, c1[c1i], f0
)
);
}
/**
* @dev Coalesce supportsInterface from inherited contracts.
*/
function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
} | * @dev Coalesce supportsInterface from inherited contracts./ | function supportsInterface(bytes4 interfaceId) public view override(ERC721, ERC721Enumerable) returns (bool) {
return super.supportsInterface(interfaceId);
}
| 7,702,917 | [
1,
4249,
24827,
6146,
1358,
628,
12078,
20092,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
3849,
12,
654,
39,
27,
5340,
16,
4232,
39,
27,
5340,
3572,
25121,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2240,
18,
28064,
1358,
12,
5831,
548,
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
] |
pragma solidity ^0.5.0;
import "../token/KIP7/KIP7Pausable.sol";
import "./PauserRoleMock.sol";
// mock class using KIP7Pausable
contract KIP7PausableMock is KIP7Pausable, PauserRoleMock {
constructor (address initialAccount, uint initialBalance) public {
_mint(initialAccount, initialBalance);
}
}
| mock class using KIP7Pausable | contract KIP7PausableMock is KIP7Pausable, PauserRoleMock {
constructor (address initialAccount, uint initialBalance) public {
_mint(initialAccount, initialBalance);
}
}
| 1,789,991 | [
1,
22851,
667,
1450,
1475,
2579,
27,
16507,
16665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
1475,
2579,
27,
16507,
16665,
9865,
353,
1475,
2579,
27,
16507,
16665,
16,
21800,
1355,
2996,
9865,
288,
203,
565,
3885,
261,
2867,
2172,
3032,
16,
2254,
2172,
13937,
13,
1071,
288,
203,
3639,
389,
81,
474,
12,
6769,
3032,
16,
2172,
13937,
1769,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x11b2164DDf1C3c0a420cEaD050d422B26530d11C/sources/contracts/facets/ERC712/ERC712Lib.sol | @dev Initializes the storage with app name and version @param name The name of the app as used for the EIP712 domain separator. @param version The version of the app as used for the EIP712 domain separator. l._hashedName = keccak256(bytes(l._name)); l._hashedVersion = keccak256(bytes(l._version)); Reset prior values in storage if upgrading | function init(string memory name, string memory version) internal {
ERC712Storage.Layout storage l = ERC712Storage.layout();
l._name = name;
l._version = version;
l._hashedName = 0;
l._hashedVersion = 0;
}
| 9,188,799 | [
1,
9685,
326,
2502,
598,
595,
508,
471,
1177,
225,
508,
1021,
508,
434,
326,
595,
487,
1399,
364,
326,
512,
2579,
27,
2138,
2461,
4182,
18,
225,
1177,
1021,
1177,
434,
326,
595,
487,
1399,
364,
326,
512,
2579,
27,
2138,
2461,
4182,
18,
328,
6315,
2816,
329,
461,
273,
417,
24410,
581,
5034,
12,
3890,
12,
80,
6315,
529,
10019,
328,
6315,
2816,
329,
1444,
273,
417,
24410,
581,
5034,
12,
3890,
12,
80,
6315,
1589,
10019,
7151,
6432,
924,
316,
2502,
309,
731,
15210,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1208,
12,
1080,
3778,
508,
16,
533,
3778,
1177,
13,
2713,
288,
203,
3639,
4232,
39,
27,
2138,
3245,
18,
3744,
2502,
328,
273,
4232,
39,
27,
2138,
3245,
18,
6741,
5621,
203,
203,
3639,
328,
6315,
529,
273,
508,
31,
203,
3639,
328,
6315,
1589,
273,
1177,
31,
203,
203,
3639,
328,
6315,
2816,
329,
461,
273,
374,
31,
203,
3639,
328,
6315,
2816,
329,
1444,
273,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/ERC721.sol
// eterart-contract
// contracts/ERC721.sol
pragma solidity ^0.4.24;
/**
* @title ERC-721 contract interface.
*/
contract ERC721 {
// ERC20 compatible functions.
function name() public constant returns (string);
function symbol() public constant returns (string);
function totalSupply() public constant returns (uint256);
function balanceOf(address _owner) public constant returns (uint);
// Functions that define ownership.
function ownerOf(uint256 _tokenId) public constant returns (address);
function approve(address _to, uint256 _tokenId) public;
function takeOwnership(uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint);
// Token metadata.
function tokenMetadata(uint256 _tokenId) public constant returns (string);
// Events.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
}
// File: contracts/EterArt.sol
// eterart-contract
// contracts/EterArt.sol
pragma solidity ^0.4.24;
/**
* @title EterArt contract.
*/
contract EterArt is ERC721 {
// Art structure for tokens ownership registry.
struct Art {
uint256 price;
address owner;
address newOwner;
}
struct Token {
uint256[] items;
mapping(uint256 => uint) lookup;
}
// Mapping from token ID to owner.
mapping (address => Token) internal ownedTokens;
// All minted tokens number (ERC-20 compatibility).
uint256 public totalTokenSupply;
// Token issuer address
address public _issuer;
// Tokens ownership registry.
mapping (uint => Art) public registry;
// Token metadata base URL.
string public baseInfoUrl = "https://www.eterart.com/art/";
// Fee in percents
uint public feePercent = 5;
// Change price event
event ChangePrice(uint indexed token, uint indexed price);
/**
* @dev Constructor sets the `issuer` of the contract to the sender
* account.
*/
constructor() public {
_issuer = msg.sender;
}
/**
* @return the address of the issuer.
*/
function issuer() public view returns(address) {
return _issuer;
}
/**
* @dev Reject all Ether from being sent here. (Hopefully, we can prevent user accidents.)
*/
function() external payable {
require(msg.sender == address(this));
}
/**
* @dev Gets token name (ERC-20 compatibility).
* @return string token name.
*/
function name() public constant returns (string) {
return "EterArt";
}
/**
* @dev Gets token symbol (ERC-20 compatibility).
* @return string token symbol.
*/
function symbol() public constant returns (string) {
return "WAW";
}
/**
* @dev Gets token URL.
* @param _tokenId uint256 ID of the token to get URL of.
* @return string token URL.
*/
function tokenMetadata(uint256 _tokenId) public constant returns (string) {
return strConcat(baseInfoUrl, strConcat("0x", uint2hexstr(_tokenId)));
}
/**
* @dev Gets contract all minted tokens number.
* @return uint256 contract all minted tokens number.
*/
function totalSupply() public constant returns (uint256) {
return totalTokenSupply;
}
/**
* @dev Gets tokens number of specified address.
* @param _owner address to query tokens number of.
* @return uint256 number of tokens owned by the specified address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
balance = ownedTokens[_owner].items.length;
}
/**
* @dev Gets token by index of specified address.
* @param _owner address to query tokens number of.
* @param _index uint256 index of the token to get.
* @return uint256 token ID from specified address tokens list by specified index.
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint tokenId) {
tokenId = ownedTokens[_owner].items[_index];
}
/**
* @dev Approve token ownership transfer to another address.
* @param _to address to change token ownership to.
* @param _tokenId uint256 token ID to change ownership of.
*/
function approve(address _to, uint256 _tokenId) public {
require(_to != msg.sender);
require(registry[_tokenId].owner == msg.sender);
registry[_tokenId].newOwner = _to;
emit Approval(registry[_tokenId].owner, _to, _tokenId);
}
/**
* @dev Internal method that transfer token to another address.
* Run some checks and internal contract data manipulations.
* @param _to address new token owner address.
* @param _tokenId uint256 token ID to transfer to specified address.
*/
function _transfer(address _to, uint256 _tokenId) internal {
if (registry[_tokenId].owner != address(0)) {
require(registry[_tokenId].owner != _to);
removeByValue(registry[_tokenId].owner, _tokenId);
}
else {
totalTokenSupply = totalTokenSupply + 1;
}
require(_to != address(0));
push(_to, _tokenId);
emit Transfer(registry[_tokenId].owner, _to, _tokenId);
registry[_tokenId].owner = _to;
registry[_tokenId].newOwner = address(0);
registry[_tokenId].price = 0;
}
/**
* @dev Take ownership of specified token.
* Only if current token owner approve that.
* @param _tokenId uint256 token ID to take ownership of.
*/
function takeOwnership(uint256 _tokenId) public {
require(registry[_tokenId].newOwner == msg.sender);
_transfer(msg.sender, _tokenId);
}
/**
* @dev Change baseInfoUrl contract property value.
* @param url string new baseInfoUrl value.
*/
function changeBaseInfoUrl(string url) public {
require(msg.sender == _issuer);
baseInfoUrl = url;
}
/**
* @dev Change issuer contract address.
* @param _to address of new contract issuer.
*/
function changeIssuer(address _to) public {
require(msg.sender == _issuer);
_issuer = _to;
}
/**
* @dev Withdraw all contract balance value to contract issuer.
*/
function withdraw() public {
require(msg.sender == _issuer);
withdraw(_issuer, address(this).balance);
}
/**
* @dev Withdraw all contract balance value to specified address.
* @param _to address to transfer value.
*/
function withdraw(address _to) public {
require(msg.sender == _issuer);
withdraw(_to, address(this).balance);
}
/**
* @dev Withdraw specified wei number to address.
* @param _to address to transfer value.
* @param _value uint wei amount value.
*/
function withdraw(address _to, uint _value) public {
require(msg.sender == _issuer);
require(_value <= address(this).balance);
_to.transfer(address(this).balance);
}
/**
* @dev Gets specified token owner address.
* @param token uint256 token ID.
* @return address specified token owner address.
*/
function ownerOf(uint256 token) public constant returns (address owner) {
owner = registry[token].owner;
}
/**
* @dev Gets specified token price.
* @param token uint256 token ID.
* @return uint specified token price.
*/
function getPrice(uint token) public view returns (uint) {
return registry[token].price;
}
/**
* @dev Direct transfer specified token to another address.
* @param _to address new token owner address.
* @param _tokenId uint256 token ID to transfer to specified address.
*/
function transfer(address _to, uint256 _tokenId) public {
require(registry[_tokenId].owner == msg.sender);
_transfer(_to, _tokenId);
}
/**
* @dev Change specified token price.
* Used for: change token price,
* withdraw token from sale (set token price to 0 (zero))
* and for put up token for sale (set token price > 0)
* @param token uint token ID to change price of.
* @param price uint new token price.
*/
function changePrice(uint token, uint price) public {
require(registry[token].owner == msg.sender);
registry[token].price = price;
emit ChangePrice(token, price);
}
/**
* @dev Buy specified token if it's marked as for sale (token price > 0).
* Run some checks, calculate fee and transfer token to msg.sender.
* @param _tokenId uint token ID to buy.
*/
function buy(uint _tokenId) public payable {
require(registry[_tokenId].price > 0);
uint fee = ((registry[_tokenId].price / 100) * feePercent);
uint value = msg.value - fee;
require(registry[_tokenId].price <= value);
registry[_tokenId].owner.transfer(value);
_transfer(msg.sender, _tokenId);
}
/**
* @dev Mint token.
*/
function mint(uint _tokenId, address _to) public {
require(msg.sender == _issuer);
require(registry[_tokenId].owner == 0x0);
_transfer(_to, _tokenId);
}
/**
* @dev Mint token.
*/
function mint(
string length,
uint _tokenId,
uint price,
uint8 v,
bytes32 r,
bytes32 s
) public payable {
string memory m_price = uint2hexstr(price);
string memory m_token = uint2hexstr(_tokenId);
require(msg.value >= price);
require(ecrecover(keccak256("\x19Ethereum Signed Message:\n", length, m_token, m_price), v, r, s) == _issuer);
require(registry[_tokenId].owner == 0x0);
_transfer(msg.sender, _tokenId);
}
/**
* UTILS
*/
/**
* @dev Add token to specified address tokens list.
* @param owner address address of token owner to add token to.
* @param value uint token ID to add.
*/
function push(address owner, uint value) private {
if (ownedTokens[owner].lookup[value] > 0) {
return;
}
ownedTokens[owner].lookup[value] = ownedTokens[owner].items.push(value);
}
/**
* @dev Remove token by ID from specified address tokens list.
* @param owner address address of token owner to remove token from.
* @param value uint token ID to remove.
*/
function removeByValue(address owner, uint value) private {
uint index = ownedTokens[owner].lookup[value];
if (index == 0) {
return;
}
if (index < ownedTokens[owner].items.length) {
uint256 lastItem = ownedTokens[owner].items[ownedTokens[owner].items.length - 1];
ownedTokens[owner].items[index - 1] = lastItem;
ownedTokens[owner].lookup[lastItem] = index;
}
ownedTokens[owner].items.length -= 1;
delete ownedTokens[owner].lookup[value];
}
/**
* @dev String concatenation.
* @param _a string first string.
* @param _b string second string.
* @return string result of string concatenation.
*/
function strConcat(string _a, string _b) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory abcde = new string(_ba.length + _bb.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
return string(babcde);
}
/**
* @dev Convert long to hex string.
* @param i uint value to convert.
* @return string specified value converted to hex string.
*/
function uint2hexstr(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint length;
while (j != 0) {
length++;
j = j >> 4;
}
uint mask = 15;
bytes memory bstr = new bytes(length);
uint k = length - 1;
while (i != 0) {
uint curr = (i & mask);
bstr[k--] = curr > 9 ? byte(55 + curr) : byte(48 + curr); // 55 = 65 - 10
i = i >> 4;
}
return string(bstr);
}
} | Tokens ownership registry. | mapping (uint => Art) public registry;
| 14,042,355 | [
1,
5157,
23178,
4023,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
516,
9042,
13,
1071,
4023,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../ERC677/ERC677.sol";
import "../Flan.sol";
import "./ProposalFactory.sol";
import "../facades/SwapFactoryLike.sol";
import "../facades/UniPairLike.sol";
import "./Governable.sol";
library TransferHelper {
function ERC20NetTransfer(
address token,
address from,
address to,
int256 amount
) public {
if (amount > 0) {
require(IERC20(token).transferFrom(from, to, uint256(amount)), "LimboDAO: ERC20 transfer from failed.");
} else {
require(IERC20(token).transfer(from, uint256(amount * (-1))), "LimboDAO: ERC20 transfer failed.");
}
}
}
enum FateGrowthStrategy {
straight,
directRoot,
indirectTwoRootEye
}
enum ProposalDecision {
voting,
approved,
rejected
}
struct DomainConfig {
address limbo;
address flan;
address eye;
address fate;
bool live;
address flashGoverner;
address sushiFactory;
address uniFactory;
}
struct ProposalConfig {
uint256 votingDuration;
uint256 requiredFateStake;
address proposalFactory; //check this for creating proposals
}
struct ProposalState {
int256 fate;
ProposalDecision decision;
address proposer;
uint256 start;
Proposal proposal;
}
//rateCrate
struct FateState {
uint256 fatePerDay;
uint256 fateBalance;
uint256 lastDamnAdjustment;
}
struct AssetClout {
uint256 fateWeight;
uint256 balance;
}
///@title Limbo DAO
///@author Justin Goro
/**@notice
*This is the first MicroDAO associated with MorgothDAO. A MicroDAO manages parameterization of running dapps without having
*control over existential functionality. This is not to say that some of the decisions taken are not critical but that the domain
*of influence is confined to the local Dapp - Limbo in this case.
* LimboDAO has two forms of decision making: proposals and flash governance. For proposals, voting power is required. Voting power in LimboDAO is measured
* by a points system called Fate. Staking EYE or an EYE based LP earns Fate at a quadratic rate. Fate can be used to list a proposal for voting or to vote.
* Using Fate to make a governance decisions spens it out of existince. So Fate reflects the opportunity cost of staking.
* Flash governance is for instant decision making that cannot wait for voting to occur. Best used for small tweaks to parameters or emergencies.
* Flash governance requires a governance asset (EYE) be staked at the time of the execution. The asset cannot be withdrawn for a certain period of time,
* allowing for Fate holders to vote on the legitimacy of the decision. If the decision is considered malicious, the staked EYE is burnt.
*/
///@dev Contracts subject to LimboDAO must inherit the Governable abstract contract.
contract LimboDAO is Ownable {
event daoKilled(address newOwner);
event proposalLodged(address proposal, address proposer);
event voteCast(address voter, address proposal, int256 fateCast);
event assetApproval(address asset, bool appoved);
event proposalExecuted(address proposal, bool approved);
event assetBurnt(address burner, address asset, uint256 fateCreated);
using TransferHelper for address;
uint256 constant ONE = 1 ether;
uint256 precision = 1e9;
DomainConfig public domainConfig;
ProposalConfig public proposalConfig;
/**@notice for staking EYE, we simply take the square root of staked amount.
* For LP tokens, only half the value of the token is EYE so it's tempting to take the square root for the EYE balance. However this punishes the holder by ignoring the cost incurred by supplying the other asset. Since the other asset at rest is equal in value to the EYE balance, we just multiply the calculation by 2.
*/
mapping(address => FateGrowthStrategy) public fateGrowthStrategy;
mapping(address => bool) public assetApproved;
mapping(address => FateState) public fateState; //lateDate
//Fate is earned per day. Keeping track of relative staked values, we can increment user balance
mapping(address => mapping(address => AssetClout)) public stakedUserAssetWeight; //user->asset->weight
ProposalState public currentProposalState;
ProposalState public previousProposalState;
// Since staking EYE precludes it from earning Flan on Limbo, fateToFlan can optionally be set to a non zero number to allow fat holders to spend their fate for Flan.
uint256 public fateToFlan;
modifier isLive() {
require(domainConfig.live, "LimboDAO: DAO is not live.");
_;
}
///@param flashGovernor oversees flash governance cryptoeconomics
function setFlashGoverner(address flashGovernor) public onlyOwner {
domainConfig.flashGoverner = flashGovernor;
}
function nextProposal() internal {
previousProposalState = currentProposalState;
currentProposalState.proposal = Proposal(address(0));
currentProposalState.fate = 0;
currentProposalState.decision = ProposalDecision.voting;
currentProposalState.proposer = address(0);
currentProposalState.start = 0;
}
modifier onlySuccessfulProposal() {
require(successfulProposal(msg.sender), "LimboDAO: approve proposal");
_;
}
///@notice has a proposal successfully been approved?
function successfulProposal(address proposal) public view returns (bool) {
return
currentProposalState.decision == ProposalDecision.approved && proposal == address(currentProposalState.proposal);
}
modifier updateCurrentProposal() {
incrementFateFor(_msgSender());
if (address(currentProposalState.proposal) != address(0)) {
uint256 durationSinceStart = block.timestamp - currentProposalState.start;
if (
durationSinceStart >= proposalConfig.votingDuration && currentProposalState.decision == ProposalDecision.voting
) {
if (currentProposalState.fate > 0) {
currentProposalState.decision = ProposalDecision.approved;
currentProposalState.proposal.orchestrateExecute();
fateState[currentProposalState.proposer].fateBalance += proposalConfig.requiredFateStake;
} else {
currentProposalState.decision = ProposalDecision.rejected;
}
emit proposalExecuted(
address(currentProposalState.proposal),
currentProposalState.decision == ProposalDecision.approved
);
nextProposal();
}
}
_;
}
modifier incrementFate() {
incrementFateFor(_msgSender());
_;
}
function incrementFateFor(address user) public {
FateState storage state = fateState[user];
state.fateBalance += (state.fatePerDay * (block.timestamp - state.lastDamnAdjustment)) / (1 days);
state.lastDamnAdjustment = block.timestamp;
}
///@param limbo address of Limbo
///@param flan address of Flan
///@param eye address of EYE token
///@param proposalFactory authenticates and instantiates valid proposals for voting
///@param sushiFactory is the SushiSwap Factory contract
///@param uniFactory is the UniSwapV2 Factory contract
///@param precisionOrderOfMagnitude when comparing fractional values, it's not necessary to get every last digit right
///@param sushiLPs valid EYE containing LP tokens elligible for earning Fate through staking
///@param uniLPs valid EYE containing LP tokens elligible for earning Fate through staking
function seed(
address limbo,
address flan,
address eye,
address proposalFactory,
address sushiFactory,
address uniFactory,
uint256 precisionOrderOfMagnitude,
address[] memory sushiLPs,
address[] memory uniLPs
) public onlyOwner {
_seed(limbo, flan, eye, sushiFactory, uniFactory);
proposalConfig.votingDuration = 2 days;
proposalConfig.requiredFateStake = 223 * ONE; //50000 EYE for 24 hours
proposalConfig.proposalFactory = proposalFactory;
precision = 10**precisionOrderOfMagnitude;
for (uint256 i = 0; i < sushiLPs.length; i++) {
require(UniPairLike(sushiLPs[i]).factory() == sushiFactory, "LimboDAO: invalid Sushi LP");
if (IERC20(eye).balanceOf(sushiLPs[i]) > 1000) assetApproved[sushiLPs[i]] = true;
fateGrowthStrategy[sushiLPs[i]] = FateGrowthStrategy.indirectTwoRootEye;
}
for (uint256 i = 0; i < uniLPs.length; i++) {
require(UniPairLike(uniLPs[i]).factory() == uniFactory, "LimboDAO: invalid Sushi LP");
if (IERC20(eye).balanceOf(uniLPs[i]) > 1000) assetApproved[uniLPs[i]] = true;
fateGrowthStrategy[uniLPs[i]] = FateGrowthStrategy.indirectTwoRootEye;
}
}
///@notice allows Limbo to be governed by a new DAO
///@dev functions marked by onlyOwner are governed by MorgothDAO
function killDAO(address newOwner) public onlyOwner isLive {
domainConfig.live = false;
Governable(domainConfig.flan).setDAO(newOwner);
Governable(domainConfig.limbo).setDAO(newOwner);
emit daoKilled(newOwner);
}
///@notice optional conversion rate of Fate to Flan
function setFateToFlan(uint256 rate) public onlySuccessfulProposal {
fateToFlan = rate;
}
///@notice caller spends their Fate to earn Flan
function convertFateToFlan(uint256 fate) public returns (uint256 flan) {
require(fateToFlan > 0, "LimboDAO: Fate conversion to Flan disabled.");
fateState[msg.sender].fateBalance -= fate;
flan = (fateToFlan * fate) / ONE;
Flan(domainConfig.flan).mint(msg.sender, flan);
}
/**@notice handles proposal lodging logic. A deposit of Fate is removed from the user. If the decision is a success, half the fate is returned.
* This is to encourage only lodging of proposals that are likely to succeed.
* @dev not for external calling. Use the proposalFactory to lodge a proposal instead.
*/
function makeProposal(address proposal, address proposer) public updateCurrentProposal {
address sender = _msgSender();
require(sender == proposalConfig.proposalFactory, "LimboDAO: only Proposal Factory");
require(address(currentProposalState.proposal) == address(0), "LimboDAO: active proposal.");
fateState[proposer].fateBalance = fateState[proposer].fateBalance - proposalConfig.requiredFateStake * 2;
currentProposalState.proposal = Proposal(proposal);
currentProposalState.decision = ProposalDecision.voting;
currentProposalState.fate = 0;
currentProposalState.proposer = proposer;
currentProposalState.start = block.timestamp;
emit proposalLodged(proposal, proposer);
}
///@notice handles proposal voting logic.
///@param proposal contract to be voted on
///@param fate positive is YES, negative is NO. Absolute value is deducted from caller.
function vote(address proposal, int256 fate) public incrementFate isLive {
require(
proposal == address(currentProposalState.proposal), //this is just to protect users with out of sync UIs
"LimboDAO: stated proposal does not match current proposal"
);
require(currentProposalState.decision == ProposalDecision.voting, "LimboDAO: voting on proposal closed");
if (block.timestamp - currentProposalState.start > proposalConfig.votingDuration - 1 hours) {
int256 currentFate = currentProposalState.fate;
//check if voting has ended
if (block.timestamp - currentProposalState.start > proposalConfig.votingDuration) {
revert("LimboDAO: voting for current proposal has ended.");
} else if (
//The following if statement checks if the vote is flipped by fate
fate * currentFate < 0 && //sign different
(fate + currentFate) * fate > 0 //fate flipped current fate onto the same side of zero as fate
) {
//extend voting duration when vote flips decision. Suggestion made by community member
currentProposalState.start = currentProposalState.start + 2 hours;
}
}
uint256 cost = fate > 0 ? uint256(fate) : uint256(-fate);
fateState[_msgSender()].fateBalance = fateState[_msgSender()].fateBalance - cost;
currentProposalState.fate += fate;
emit voteCast(_msgSender(), proposal, fate);
}
///@notice pushes the decision to execute a successful proposal. For convenience only
function executeCurrentProposal() public updateCurrentProposal {}
///@notice parameterizes the voting
///@param requiredFateStake the amount of Fate required to lodge a proposal
///@param votingDuration the duration of voting in seconds
///@param proposalFactory the address of the proposal factory
function setProposalConfig(
uint256 votingDuration,
uint256 requiredFateStake,
address proposalFactory
) public onlySuccessfulProposal {
proposalConfig.votingDuration = votingDuration;
proposalConfig.requiredFateStake = requiredFateStake;
proposalConfig.proposalFactory = proposalFactory;
}
///@notice Assets approved for earning Fate
function setApprovedAsset(address asset, bool approved) public onlySuccessfulProposal {
assetApproved[asset] = approved;
fateGrowthStrategy[asset] = FateGrowthStrategy.indirectTwoRootEye;
emit assetApproval(asset, approved);
}
///@notice handles staking logic for EYE and EYE based assets so that correct rate of fate is earned.
///@param finalAssetBalance after staking, what is the final user balance on LimboDAO of the asset in question
///@param finalEYEBalance if EYE is being staked, this value is the same as finalAssetBalance but for LPs it's about half
///@param rootEYE offload high gas arithmetic to the client. Cheap to verify. Square root in fixed point requires Babylonian algorithm
///@param asset the asset being staked
function setEYEBasedAssetStake(
uint256 finalAssetBalance,
uint256 finalEYEBalance,
uint256 rootEYE,
address asset
) public isLive incrementFate {
require(assetApproved[asset], "LimboDAO: illegal asset");
address sender = _msgSender();
FateGrowthStrategy strategy = fateGrowthStrategy[asset];
//verifying that rootEYE value is accurate within precision.
uint256 rootEYESquared = rootEYE * rootEYE;
uint256 rootEYEPlusOneSquared = (rootEYE + 1) * (rootEYE + 1);
require(
rootEYESquared <= finalEYEBalance && rootEYEPlusOneSquared > finalEYEBalance,
"LimboDAO: Stake EYE invariant."
);
AssetClout storage clout = stakedUserAssetWeight[sender][asset];
fateState[sender].fatePerDay -= clout.fateWeight;
uint256 initialBalance = clout.balance;
//EYE
if (strategy == FateGrowthStrategy.directRoot) {
require(finalAssetBalance == finalEYEBalance, "LimboDAO: staking eye invariant.");
require(asset == domainConfig.eye);
clout.fateWeight = rootEYE;
clout.balance = finalAssetBalance;
fateState[sender].fatePerDay += rootEYE;
} else if (strategy == FateGrowthStrategy.indirectTwoRootEye) {
//LP
clout.fateWeight = 2 * rootEYE;
fateState[sender].fatePerDay += clout.fateWeight;
uint256 actualEyeBalance = IERC20(domainConfig.eye).balanceOf(asset);
require(actualEyeBalance > 0, "LimboDAO: No EYE");
uint256 totalSupply = IERC20(asset).totalSupply();
uint256 eyePerUnit = (actualEyeBalance * ONE) / totalSupply;
uint256 impliedEye = (eyePerUnit * finalAssetBalance) / (ONE * precision);
finalEYEBalance /= precision;
require(
finalEYEBalance == impliedEye, //precision cap
"LimboDAO: stake invariant check 2."
);
clout.balance = finalAssetBalance;
} else {
revert("LimboDAO: asset growth strategy not accounted for");
}
int256 netBalance = int256(finalAssetBalance) - int256(initialBalance);
asset.ERC20NetTransfer(sender, address(this), netBalance);
}
/**
*@notice Acquiring enough fate to either influence a decision or to lodge a proposal can take very long.
* If a very important decision has to be acted on via a proposal, the option exists to buy large quantities for fate instantly by burning an EYE based asset
* This may be necessary if a vote is nearly complete by the looming outcome is considered unacceptable.
* While Fate accumulation is quadratic for staking, burning is linear and subject to a factor of 10. This gives whales effective veto power but at the cost of a permanent
* loss of EYE.
*@param asset the asset to burn and can be EYE or EYE based assets
*@param amount the amount of asset to burn
*/
function burnAsset(address asset, uint256 amount) public isLive incrementFate {
require(assetApproved[asset], "LimboDAO: illegal asset");
address sender = _msgSender();
require(ERC677(asset).transferFrom(sender, address(this), amount), "LimboDAO: transferFailed");
uint256 fateCreated = fateState[_msgSender()].fateBalance;
if (asset == domainConfig.eye) {
fateCreated = amount * 10;
ERC677(domainConfig.eye).burn(amount);
} else {
uint256 actualEyeBalance = IERC20(domainConfig.eye).balanceOf(asset);
require(actualEyeBalance > 0, "LimboDAO: No EYE");
uint256 totalSupply = IERC20(asset).totalSupply();
uint256 eyePerUnit = (actualEyeBalance * ONE) / totalSupply;
uint256 impliedEye = (eyePerUnit * amount) / ONE;
fateCreated = impliedEye * 20;
}
fateState[_msgSender()].fateBalance += fateCreated;
emit assetBurnt(_msgSender(), asset, fateCreated);
}
///@notice grants unlimited Flan minting power to an address.
function approveFlanMintingPower(address minter, bool enabled) public onlySuccessfulProposal isLive {
Flan(domainConfig.flan).increaseMintAllowance(minter, enabled ? type(uint256).max : 0);
}
///@notice call this after initial config is complete.
function makeLive() public onlyOwner {
require(
Governable(domainConfig.limbo).DAO() == address(this) && Governable(domainConfig.flan).DAO() == address(this),
"LimboDAO: transfer ownership of limbo and flan."
);
domainConfig.live = true;
}
///@notice if the DAO is being dismantled, it's necessary to transfer any owned items
function transferOwnershipOfThing(address thing, address destination) public onlySuccessfulProposal {
Ownable(thing).transferOwnership(destination);
}
function timeRemainingOnProposal() public view returns (uint256) {
require(currentProposalState.decision == ProposalDecision.voting, "LimboDAO: proposal finished.");
uint256 elapsed = block.timestamp - currentProposalState.start;
if (elapsed > proposalConfig.votingDuration) return 0;
return proposalConfig.votingDuration - elapsed;
}
/**@notice seed is a goro idiom for initialize that you tend to find in all the dapps I've written.
* I prefer initialization funcitons to parameterized solidity constructors for reasons beyond the scope of this comment.
*/
function _seed(
address limbo,
address flan,
address eye,
address sushiFactory,
address uniFactory
) internal {
require(domainConfig.flashGoverner != address(0), "LimboDAO: flashGovernor not initialized.");
domainConfig.limbo = limbo;
domainConfig.flan = flan;
domainConfig.eye = eye;
domainConfig.uniFactory = uniFactory;
domainConfig.sushiFactory = sushiFactory;
assetApproved[eye] = true;
fateGrowthStrategy[eye] = FateGrowthStrategy.directRoot;
}
function getFlashGoverner() external view returns (address) {
require(domainConfig.flashGoverner != address(0), "LimboDAO: no flash governer");
return domainConfig.flashGoverner;
}
}
| @notice pushes the decision to execute a successful proposal. For convenience only | function executeCurrentProposal() public updateCurrentProposal {}
| 7,274,572 | [
1,
6206,
281,
326,
14604,
358,
1836,
279,
6873,
14708,
18,
2457,
13553,
1338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1836,
3935,
14592,
1435,
1071,
1089,
3935,
14592,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x2762B1C6480757395788cB3C1458c507f9d44378/sources/zero.sol | * @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+1).toString(),".json")) : "";
}
| 9,126,928 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
3639,
533,
3778,
1026,
3098,
273,
389,
1969,
3098,
5621,
203,
3639,
327,
1731,
12,
1969,
3098,
2934,
2469,
480,
374,
692,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
3098,
16,
2206,
3113,
261,
2316,
548,
15,
21,
2934,
10492,
9334,
9654,
1977,
6,
3719,
294,
1408,
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
] |
// 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);
}
/**
* @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);
function keyOfRoot(uint256 root) external view returns (address);
/**
* @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;
}
/**
* @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);
}
}
/*
* @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;
}
}
/**
* @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;
address private _pending_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");
_;
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function proposeOwner(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new pending owner is the zero address");
_pending_owner = newOwner;
}
function claimOwner() public virtual {
require(_pending_owner == msg.sender, "Ownable: msg.sender is not the pending owner");
address oldOwner = _owner;
_owner = _pending_owner;
_pending_owner = address(0);
emit OwnershipTransferred(oldOwner, _owner);
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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;
}
}
/**
* @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;
}
function keyOfRoot(uint256 root) public view virtual override returns (address) {
return _owners[root];
}
/**
* @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(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @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 the assets stored by the contract.
*/
function assets() external view returns (address);
/**
* @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);
function rootOfKey(address key) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
address private _assets;
/**
* @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;
}
function assets() external view virtual override returns (address) {
return _assets;
}
/**
* @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];
}
function rootOfKey(address key) public view virtual override returns (uint256) {
return ERC721.balanceOf(key) == 0 ? type(uint256).max : _ownedTokens[key][0];
}
/**
* @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 != 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);
require(length == 0, "Root: already exists!");
_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).
require(ERC721.balanceOf(from) == 1, "Root: not exists!");
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][0];
}
/**
* @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();
}
function _setAssets(address assets_) internal {
_assets = assets_;
}
}
contract Root is ERC721Enumerable, ReentrancyGuard, Ownable {
using Address for address;
uint256 public start_time = 0;
uint256 public deploy_time = 0;
uint256 public MAX_TOTAL_SUPPLY = 21000000;
function claim() external nonReentrant {
require(claimable(), "not claimable");
uint256 ts = totalSupply();
if (ts == 2100) {
start_time = deploy_time + (21 days);
} else if (ts == 21000) {
start_time = deploy_time + (21 * 4 days);
} else if (ts == 210000) {
start_time = deploy_time + (21 * 4 * 4 days);
} else if (ts == 2100000) {
start_time = deploy_time + (21 * 4 * 4 * 4 days);
}
_safeMint(_msgSender(), ts);
}
function claimable() public view returns (bool) {
return block.timestamp >= start_time && totalSupply() < MAX_TOTAL_SUPPLY;
}
function claimableId() external view returns (uint256) {
return claimable() ? totalSupply() : type(uint256).max;
}
function setAssets(address _assets) external onlyOwner {
super._setAssets(_assets);
}
function expand() external onlyOwner {
require(totalSupply() == MAX_TOTAL_SUPPLY, "ROOT: totalSupply not equal to current max_total_supply");
MAX_TOTAL_SUPPLY = MAX_TOTAL_SUPPLY * 10;
}
constructor() ERC721("ROOT", "ROOT") Ownable() {
deploy_time = block.timestamp;
}
} | * @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;
address private _pending_owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
function proposeOwner(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new pending owner is the zero address");
_pending_owner = newOwner;
}
function claimOwner() public virtual {
require(_pending_owner == msg.sender, "Ownable: msg.sender is not the pending owner");
address oldOwner = _owner;
_owner = _pending_owner;
_pending_owner = address(0);
emit OwnershipTransferred(oldOwner, _owner);
}
}
| 13,826,506 | [
1,
8924,
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,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
565,
1758,
3238,
389,
9561,
67,
8443,
31,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
2416,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
565,
3885,
1435,
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,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
389,
542,
5541,
12,
2867,
394,
5541,
13,
3238,
288,
203,
3639,
1758,
1592,
5541,
273,
389,
8443,
31,
203,
3639,
389,
8443,
273,
394,
5541,
31,
203,
3639,
3626,
14223,
9646,
5310,
1429,
4193,
12,
1673,
5541,
16,
394,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
450,
4150,
5541,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
4634,
3410,
353,
326,
3634,
1758,
8863,
203,
3639,
389,
9561,
67,
8443,
273,
394,
5541,
31,
203,
565,
289,
203,
203,
565,
445,
7516,
5541,
1435,
1071,
5024,
288,
203,
3639,
2583,
24899,
9561,
67,
8443,
422,
1234,
18,
15330,
16,
315,
5460,
429,
30,
1234,
18,
15330,
353,
486,
326,
2
] |
pragma solidity ^0.4.24;
import "./ownership/Ownable.sol";
import "./cryptography/ECDSA.sol";
// import "./interfaces/IERC20.sol";
/**
* @title Micro payments contract for m2m payments based on one-to-many state channel architecture
* @notice Only contract owner can add or remove trusted contract addresses
*/
contract M2MMicroPayments is Ownable{
// number of blocks to wait after an uncooperative close is initiated
uint256 public challengePeriod;
// Future TO-DO - implement upgradeable proxy architecture
// contract semantic version
string public constant VERSION = '0.0.1';
struct Channel{
uint256 deposit;
uint256 openBlockNumber;
}
struct ClosingRequest{
uint256 closingBalance;
uint256 settleBlockNumber;
}
// IERC20 public token;
mapping (bytes32 => Channel) public channels;
mapping (bytes32 => ClosingRequest) public closingRequests;
mapping (address => bool) public trustedContracts;
mapping (bytes32 => uint256) public withdrawnBalances;
/**
* @notice Modifier to make a function callable only if the sender is trusted
*/
modifier isTrusted() {
require (trustedContracts[msg.sender], 'address not trusted');
_;
}
//////////
// Events
//////////
event ChannelCreated(
address indexed sender,
address indexed receiver,
uint256 deposit);
event ChannelToppedUp (
address indexed sender,
address indexed receiver,
uint256 indexed openBlockNumber,
uint256 deposit);
event ChannelCloseRequested(
address indexed sender,
address indexed receiver,
uint256 indexed openBlockNumber,
uint256 balance);
event ChannelSettled(
address indexed sender,
address indexed receiver,
uint256 indexed openBlockNumber,
uint256 balance,
uint256 receiverTokens);
event ChannelWithdraw(
address indexed sender,
address indexed receiver,
uint256 indexed openBlockNumber,
uint256 remainingBalance);
event TrustedContract(
address indexed trustedContract,
bool trustedStatus);
/////////////
// Functions
/////////////
/**
* @notice Constructor
* @param _challengePeriod A fixed number of blocks representing the challenge period
* @param _trustedContracts Array of contract addresses that can be trusted to open and top up channels on behalf of a sender
*/
constructor (
uint256 _challengePeriod,
address[] _trustedContracts)
public {
require(_challengePeriod >= 500, "challenge period must span atleast 500 blocks");
challengePeriod = _challengePeriod;
if(_trustedContracts.length >= 1){
addTrustedContracts(_trustedContracts);
}
}
/*
* External functions
*/
/**
* @notice payable function which creates a channel between `msg.sender` and `_receiver` with a net amount of `msg.value`
* @param _receiver server side of transfer
* @param _deposit amount of ETH escrowed by the client
*/
function createChannel(address _receiver, uint256 _deposit) external payable{
require(msg.value == _deposit, 'invalid deposit');
createChannelPrivate(msg.sender, _receiver, _deposit);
}
/**
* @notice Increase the channel deposit with `_addedDeposit`
* @param _receiver Server side of transfer
* @param _openBlockNumber Block number at which the channel was created
* @param _addedDeposit TopUp amount
*/
function topUp(
address _receiver,
uint256 _openBlockNumber,
uint256 _addedDeposit)
external payable {
require(msg.value == _addedDeposit, 'invalid topUp value');
updateInternalBalanceStructs(
msg.sender,
_receiver,
_openBlockNumber,
_addedDeposit
);
}
/**
* @notice Allows channel receiver to withdraw tokens
* @param _openBlockNumber Block number at which the channel was created
* @param _balance Partial or total amount of tokens owed by the sender to the receiver
* @param _balanceMsgSig The balance message signed by the sender
*/
function withdraw(
uint256 _openBlockNumber,
uint256 _balance,
bytes _balanceMsgSig)
external {
require(_balance > 0, "zero withdrawal amount");
// Derive sender address from signed balance proof
address sender = extractBalanceProofSignature(
msg.sender,
_openBlockNumber,
_balance,
_balanceMsgSig
);
bytes32 key = getKey(sender, msg.sender, _openBlockNumber);
require(channels[key].openBlockNumber > 0, 'channel does not exist');
require (closingRequests[key].settleBlockNumber == 0, 'channel is in the challenge period');
require (_balance <= channels[key].deposit, 'withdrawal amount must be smaller than the channel deposit');
require (withdrawnBalances[key] < _balance, 'invalid balance');
uint256 remainingBalance = _balance - withdrawnBalances[key];
withdrawnBalances[key] = _balance;
(msg.sender).transfer(remainingBalance);
emit ChannelWithdraw(sender, msg.sender, _openBlockNumber, remainingBalance);
}
/**
* @notice Function called by the sender, receiver or a delegate, with all the needed signatures to close the channel and settle immediately
* @param _receiver Server side of transfer
* @param _openBlockNumber The block number at which a channel between the sender and receiver was created.
* @param _balance Partial or total amount owed by the sender to the receiver
* @param _balanceMsgSig The balance message signed by the sender
* @param _closingSig The receiver's signed balance message, containing the sender's address
*/
function cooperativeClose(
address _receiver,
uint256 _openBlockNumber,
uint192 _balance,
bytes _balanceMsgSig,
bytes _closingSig)
external {
// Derive sender address from signed balance proof
address sender = extractBalanceProofSignature(
_receiver,
_openBlockNumber,
_balance,
_balanceMsgSig
);
// Derive receiver address from closing signature
address receiver = extractClosingSignature(
sender,
_openBlockNumber,
_balance,
_closingSig
);
require(receiver == _receiver, 'invalid signatures');
// Both signatures have been verified and the channel can be settled.
settleChannel(sender, receiver, _openBlockNumber, _balance);
}
/**
* @notice Sender requests the closing of the channel and starts the challenge period - This can only happen once
* @param _receiver Server side of transfer
* @param _openBlockNumber The block number at which a channel between the sender and receiver was created.
* @param _balance Partial or total amount owed by the sender to the receiver
*/
function uncooperativeClose(
address _receiver,
uint256 _openBlockNumber,
uint256 _balance)
external {
bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber);
require(channels[key].openBlockNumber > 0, 'channel does not exist');
require(closingRequests[key].settleBlockNumber == 0, 'challenge period already started');
require(_balance <= channels[key].deposit, 'invalid balance');
// Mark channel as closed
closingRequests[key].settleBlockNumber = block.number + challengePeriod;
require(closingRequests[key].settleBlockNumber > block.number, 'challenge period not set correctly');
closingRequests[key].closingBalance = _balance;
emit ChannelCloseRequested(msg.sender, _receiver, _openBlockNumber, _balance);
}
/**
* @notice Function called by the sender after the challenge period has ended, in order to settle and delete the channel, in case the receiver has not closed the channel himself
* @param _receiver Server side of transfer
* @param _openBlockNumber The block number at which a channel between the sender and receiver was created
*/
function settle(address _receiver, uint256 _openBlockNumber) external {
bytes32 key = getKey(msg.sender, _receiver, _openBlockNumber);
// Make sure an uncooperativeClose has been initiated
require(closingRequests[key].settleBlockNumber > 0, 'challenge period has not been started');
// Make sure the challenge_period has ended
require(block.number > closingRequests[key].settleBlockNumber, 'challenge period still active');
settleChannel(msg.sender, _receiver, _openBlockNumber,
closingRequests[key].closingBalance
);
}
/**
* @notice Function for retrieving information about a channel.
* @param _sender address that want to send the micro-payment
* @param _receiver address that is to receive the micro-payment
* @param _openBlockNumber the block number at which the channel was created
* @return Channel information: unique_identifier, deposit, settleBlockNumber, closingBalance, withdrawnBalance
*/
function getChannelInfo(
address _sender,
address _receiver,
uint256 _openBlockNumber)
external view returns (bytes32, uint256, uint256, uint256, uint256) {
bytes32 key = getKey(_sender, _receiver, _openBlockNumber);
require(channels[key].openBlockNumber > 0, 'channel does not exist');
return (
key,
channels[key].deposit,
closingRequests[key].settleBlockNumber,
closingRequests[key].closingBalance,
withdrawnBalances[key]
);
}
/*
* Public functions
*/
/**
* @notice can only be called by the owner to add trusted contract addresses
* @param _trustedContracts Array of contract addresses that can be trusted to open and top up channels on behalf of a sender
*/
function addTrustedContracts(address[] _trustedContracts) onlyOwner public {
require(_trustedContracts.length >= 1, "no contract addresses provided");
for (uint256 i = 0; i < _trustedContracts.length; i++) {
if (_addressHasCode(_trustedContracts[i])) {
trustedContracts[_trustedContracts[i]] = true;
emit TrustedContract(_trustedContracts[i], true);
}
}
}
/**
* @notice can only be called by the owner to remove trusted contract addresses
* @param _trustedContracts Array of contract addresses that can no longer be trusted to open and top up channels on behalf of a sender
*/
function removeTrustedContracts(address[] _trustedContracts) onlyOwner public {
for (uint256 i = 0; i < _trustedContracts.length; i++) {
if (trustedContracts[_trustedContracts[i]]) {
trustedContracts[_trustedContracts[i]] = false;
emit TrustedContract(_trustedContracts[i], false);
}
}
}
/**
* @notice can only be called by the owner to remove trusted contract addresses
* @param _sender address that want to send the micro-payment
* @param _receiver address that is to receive the micro-payment
* @param _openBlockNumber the block number at which the channel was created
*/
function getKey(
address _sender,
address _receiver,
uint256 _openBlockNumber)
public pure returns (bytes32 data) {
return keccak256(abi.encodePacked(
_sender,
_receiver,
_openBlockNumber
));
}
/**
* @notice Returns the sender address extracted from the balance proof
* @dev Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712
* @param _receiver Address that is to receive the micro-payment
* @param _openBlockNumber Block number at which the channel was created
* @param _balance The amount owed by the sender to the receiver
* @param _balanceMsgSig The balance message signed by the sender
* @return Address of the balance proof signer
*/
function extractBalanceProofSignature(
address _receiver,
uint256 _openBlockNumber,
uint256 _balance,
bytes _balanceMsgSig)
public view returns(address) {
// TO-DO - replace legacy implementation with EIP712 implementation for signing typed data
bytes32 message_hash = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(
'string message_id',
'address receiver',
'uint256 block_created',
'uint256 balance',
'address contract'
)),
keccak256(abi.encodePacked(
'Sender balance proof signature',
_receiver,
_openBlockNumber,
_balance,
address(this)
))
));
// Derive address from signature
address signer = ECDSA.recover(message_hash, _balanceMsgSig);
return signer;
}
/**
* @notice Returns the receiver address extracted from the closing signature
* @dev Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712
* @param _sender Address that is sending the micro-payment
* @param _openBlockNumber Block number at which the channel was created
* @param _balance The amount owed by the sender to the receiver
* @param _closingSig The receiver's signed balance message, containing the sender's address
* @return Address of the closing signature signer
*/
function extractClosingSignature(
address _sender,
uint256 _openBlockNumber,
uint256 _balance,
bytes _closingSig)
public view returns (address) {
// TO-DO - replace legacy implementation with EIP712 implementation for signing typed data
bytes32 message_hash = keccak256(abi.encodePacked(
keccak256(abi.encodePacked(
'string message_id',
'address sender',
'uint256 block_created',
'uint256 balance',
'address contract'
)),
keccak256(abi.encodePacked(
'Receiver closing signature',
_sender,
_openBlockNumber,
_balance,
address(this)
))
));
// Derive address from signature
address signer = ECDSA.recover(message_hash, _closingSig);
return signer;
}
/*
* Private functions
*/
/**
* @notice can only be called by the owner to remove trusted contract addresses
* @param _sender address that want to send the micro-payment
* @param _receiver address that is to receive the micro-payment
* @param _deposit amount of ETH escrowed by the sender
*/
function createChannelPrivate(
address _sender,
address _receiver,
uint256 _deposit)
private {
// set a 1 ETH deposit limit until fully tested for security violations
require(_deposit <= 1 ether, 'deposit limit crossed');
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_sender, _receiver, block.number);
require(channels[key].deposit == 0);
require(channels[key].openBlockNumber == 0);
require(closingRequests[key].settleBlockNumber == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, openBlockNumber: block.number});
emit ChannelCreated(_sender, _receiver, _deposit);
}
/**
* @notice can only be called by the owner to remove trusted contract addresses
* @param _sender address that want to send the micro-payment
* @param _receiver address that is to receive the micro-payment
* @param _openBlockNumber Block number at which the channel was created
* @param _addedDeposit The added deposit with which the current deposit is increased
*/
function updateInternalBalanceStructs(
address _sender,
address _receiver,
uint256 _openBlockNumber,
uint256 _addedDeposit)
private {
require(_addedDeposit > 0, 'topUp amount must not be zero');
require(_openBlockNumber > 0, 'invalid openBlockNumber');
bytes32 key = getKey(_sender, _receiver, _openBlockNumber);
require(channels[key].openBlockNumber > 0, "channel does not exist");
require(closingRequests[key].settleBlockNumber == 0, "channel already closed");
require(channels[key].deposit + _addedDeposit <= 1 ether, "channel limit exceeded");
channels[key].deposit += _addedDeposit;
assert(channels[key].deposit >= _addedDeposit);
emit ChannelToppedUp(_sender, _receiver, _openBlockNumber, _addedDeposit);
}
/**
* @notice Deletes the channel and settles by transfering the balance to the receiver and the rest of the deposit back to the sender
* @param _sender address that want to send the micro-payment
* @param _receiver address that is to receive the micro-payment
* @param _openBlockNumber Block number at which the channel was created
* @param _balance The amount owed by the sender to the receiver
*/
function settleChannel(
address _sender,
address _receiver,
uint256 _openBlockNumber,
uint256 _balance)
private {
bytes32 key = getKey(_sender, _receiver, _openBlockNumber);
Channel memory channel = channels[key];
require(channel.openBlockNumber > 0, 'channel does not exist');
require(_balance <= channel.deposit, 'balance must be less than channel deposit');
require(withdrawnBalances[key] <= _balance, 'invalid balance');
// Remove closed channel structures
// channel.openBlockNumber will become 0
// Change state before transfer call
delete channels[key];
delete closingRequests[key];
// Send the unwithdrawn _balance to the receiver
uint256 receiverRemainingAmount = _balance - withdrawnBalances[key];
_receiver.transfer(receiverRemainingAmount);
// Send deposit - balance back to sender
_sender.transfer(channel.deposit - _balance);
emit ChannelSettled(
_sender,
_receiver,
_openBlockNumber,
_balance,
receiverRemainingAmount
);
}
/*
* Internal functions
*/
/**
* @notice Creates a new channel between a sender and a receiver
* @param data Bytes received
* @param offset Number of bytes to offset
* @return Extracted address
*/
function addressFromBytes (bytes data, uint256 offset) internal pure returns (address) {
bytes20 extractedAddress;
assembly {
extractedAddress := mload(add(data, offset))
}
return address(extractedAddress);
}
/**
* @notice used to verify if an address has some contract code
* @param _contract is the address of the contract
* @return True if a contract exists, false otherwise
*/
function _addressHasCode(address _contract) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(_contract)
}
return size > 0;
}
} | * @notice Function for retrieving information about a channel. @param _sender address that want to send the micro-payment @param _receiver address that is to receive the micro-payment @param _openBlockNumber the block number at which the channel was created @return Channel information: unique_identifier, deposit, settleBlockNumber, closingBalance, withdrawnBalance/ | function getChannelInfo(
address _sender,
address _receiver,
uint256 _openBlockNumber)
external view returns (bytes32, uint256, uint256, uint256, uint256) {
bytes32 key = getKey(_sender, _receiver, _openBlockNumber);
require(channels[key].openBlockNumber > 0, 'channel does not exist');
return (
key,
channels[key].deposit,
closingRequests[key].settleBlockNumber,
closingRequests[key].closingBalance,
withdrawnBalances[key]
);
}
| 997,107 | [
1,
2083,
364,
17146,
1779,
2973,
279,
1904,
18,
225,
389,
15330,
1758,
716,
2545,
358,
1366,
326,
6481,
17,
9261,
225,
389,
24454,
1758,
716,
353,
358,
6798,
326,
6481,
17,
9261,
225,
389,
3190,
1768,
1854,
326,
1203,
1300,
622,
1492,
326,
1904,
1703,
2522,
327,
5307,
1779,
30,
3089,
67,
5644,
16,
443,
1724,
16,
444,
5929,
1768,
1854,
16,
7647,
13937,
16,
598,
9446,
82,
13937,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
16454,
966,
12,
203,
3639,
1758,
389,
15330,
16,
203,
3639,
1758,
389,
24454,
16,
203,
3639,
2254,
5034,
389,
3190,
1768,
1854,
13,
203,
565,
3903,
1476,
1135,
261,
3890,
1578,
16,
2254,
5034,
16,
2254,
5034,
16,
2254,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
1731,
1578,
498,
273,
3579,
24899,
15330,
16,
389,
24454,
16,
389,
3190,
1768,
1854,
1769,
203,
3639,
2583,
12,
9114,
63,
856,
8009,
3190,
1768,
1854,
405,
374,
16,
296,
4327,
1552,
486,
1005,
8284,
203,
203,
3639,
327,
261,
203,
5411,
498,
16,
203,
5411,
5750,
63,
856,
8009,
323,
1724,
16,
203,
5411,
7647,
6421,
63,
856,
8009,
542,
5929,
1768,
1854,
16,
203,
5411,
7647,
6421,
63,
856,
8009,
19506,
13937,
16,
203,
5411,
598,
9446,
82,
38,
26488,
63,
856,
65,
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
] |
./partial_match/42/0xe9d078aa6BcE3C220636eE90eF255ad623FF5AfC/sources/LENREK1.sol | * @dev Destroys `amount` tokens from `account`, reducing the total supply. Emits a {Transfer} event with `to` set to the zero address. Requirements - `account` cannot be the zero address. - `account` must have at least `amount` tokens./ | function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
| 3,361,485 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
1375,
4631,
9191,
9299,
2822,
326,
2078,
14467,
18,
7377,
1282,
279,
288,
5912,
97,
871,
598,
1375,
869,
68,
444,
358,
326,
3634,
1758,
18,
29076,
300,
1375,
4631,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
4631,
68,
1297,
1240,
622,
4520,
1375,
8949,
68,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
70,
321,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
2713,
5024,
288,
203,
3639,
2583,
12,
4631,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
203,
3639,
389,
70,
26488,
63,
4631,
65,
273,
389,
70,
26488,
63,
4631,
8009,
1717,
12,
203,
5411,
3844,
16,
203,
5411,
315,
654,
39,
3462,
30,
18305,
3844,
14399,
11013,
6,
203,
3639,
11272,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1717,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
4631,
16,
1758,
12,
20,
3631,
3844,
1769,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
// imports en remix
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol";
// import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol";
contract GameRoom {
using SafeMath for uint;
address payable player1;
address payable player2;
uint bet;
bool isFull;
mapping (address => bytes32) moves;
mapping (address => uint) cooldowns;
mapping (address => bytes32) commitedMoves;
mapping (address => uint) selection; //tijeras => 0; papel => 1; piedra => 2
uint timeBetweenPlays = 5 minutes;
uint revealMoveCounter;
bool isOpen;
//Tiene sentido hacer esto??
modifier isPlayer(){
require(player1 == msg.sender || player2 == msg.sender, "you are not a player");
_;
}
modifier isTheHost(address _address){
require(_address == player1);
_;
}
modifier playersHaveDeposited(uint totalAmout){
require(address(this).balance == bet.mul(2), "All players must set bet to play");
_;
}
event playerMove(address _player, uint time);
event emitWinner(address _winner);
event emitDraw();
event winnerPayed(address _winner, uint _bet);
event playerTimeOut(address _player);
event playerMoveRevealed(address _player0);
event bothPlayersRevealed();
event gameIsColsed();
constructor (address payable _player1, uint _bet) payable {
player1 = _player1;
bet = _bet;
isFull = false;
revealMoveCounter = 0;
isOpen = true;
}
function setPlayer2(address payable _player2) external payable{
require(_player2.balance >= bet);
player2 = _player2;
isFull = true;
}
function getPlayer() internal view returns(uint) {
if (msg.sender == player1){
return 1;
}else{
return 2;
}
}
function getBet() external view returns (uint) {
return bet;
}
function isFullGame() external view returns (bool) {
return isFull;
}
function started() external view returns (bool) {
return moves[player1] != 0 || moves[player2] != 0;
}
function declareMove(bytes32 _move) public isPlayer() {
require(isOpen, "the game is already over, thanks for playing!");
if (getPlayer() == 1) {
require(moves[player1] == 0, "you already made a move"); //VER COMO ARREGLARLO
changeMove(_move, player1, player2);
} else {
require(moves[player2] == 0, "you already made a move"); //VER COMO ARREGLARLO
changeMove(_move, player2, player1);
}
}
function changeMove(bytes32 _move, address payable _player, address payable _rival) internal {
uint cooldown = block.timestamp;
cooldowns[_player] = cooldown;
if (cooldowns[_rival] != 0){
if (cooldowns[_player] - cooldowns[_rival] > timeBetweenPlays) {
emit playerTimeOut(_player);
_rival.transfer(bet.mul(2));
isOpen = false;
emit gameIsColsed();
return;
}
}
moves[_player] = _move;
emit playerMove(_player, cooldown);
}
function revealMove(string memory _move, bytes32 _commitedMove) public isPlayer() {
require(isOpen, "the game is already over, thanks for playing!");
if (getPlayer() == 1) {
require(commitedMoves[player1] == 0, "you already commited your move"); //VER COMO ARREGLARLO
revealMoveLogic(_move,_commitedMove);
commitedMoves[msg.sender] = _commitedMove;
revealMoveCounter.add(1);
} else {
require(commitedMoves[player2] == 0, "you already commited your move"); //VER COMO ARREGLARLO
revealMoveLogic(_move,_commitedMove);
commitedMoves[msg.sender] = _commitedMove;
revealMoveCounter.add(1);
}
if (revealMoveCounter == 2) {
emit bothPlayersRevealed();
}
}
function revealMoveLogic(string memory _move, bytes32 _commitedMove) internal{
require(isOpen, "the game is already over, thanks for playing!");
require(_commitedMove == keccak256(abi.encodePacked(_move)), "the moves are not the same");
require(revealMoveCounter <= 2,"Both players revealed their move");
bytes memory moveInBytes = bytes(_move);
if (moveInBytes[0] == 't'){
uint moveNumber = 0;
moveNumber = selection[msg.sender];
}
if (moveInBytes[0] == 'p'){
if (moveInBytes[1] == 'a') {
uint moveNumber = 1;
selection[msg.sender] = moveNumber;
} else if (moveInBytes[1] == 'i') {
uint moveNumber = 2;
selection[msg.sender] = moveNumber;
}
}
emit playerMoveRevealed(msg.sender);
}
function declareWinner() public { //MATI tengo que ver como hacer para verificar que ambos jugadores revelaron sus jugadas
require(isOpen, "the game is already over, thanks for playing!");
require(revealMoveCounter == 2, "both players have to reveal their move");
//tijeras => 0; papel => 1; piedra => 2
uint choice1 = selection[player1];
uint choice2 = selection[player2];
if(choice1 == choice2){
player1.transfer(bet);
player2.transfer(bet);
emit emitDraw();
}else if (choice1 == 0 && choice2 == 1 || choice1 == 1 && choice2 == 2 || choice1 == 2 && choice2 == 0){
player1.transfer(bet.mul(2));
emit emitWinner(player1);
}else{
player2.transfer(bet.mul(2));
emit emitWinner(player2);
}
isOpen = false;
emit gameIsColsed();
}
//for testing
function getRevealMoveCounter() public view returns(uint count){
return revealMoveCounter;
}
function getPlayer1AndBalance() public view returns (address _player1,uint256 _p1Balance){
return(player1,player1.balance);
}
function getPlayer2AndBalance() public view returns (address _player2,uint256 _p2Balance){
return(player2,player2.balance);
}
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
function deposit() external payable {
require(msg.sender.balance > bet, "You dont have the enough money");
require(msg.value == bet, "deposit the bet amount");
}
}
| VER COMO ARREGLARLO
| require(commitedMoves[player2] == 0, "you already commited your move"); | 6,385,094 | [
1,
2204,
5423,
51,
6052,
5937,
48,
985,
1502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2583,
12,
7371,
329,
19297,
63,
14872,
22,
65,
422,
374,
16,
315,
19940,
1818,
3294,
329,
3433,
3635,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Autonomy is Ownable {
address public congress;
bool init = false;
modifier onlyCongress() {
require(msg.sender == congress);
_;
}
/**
* @dev initialize a Congress contract address for this token
*
* @param _congress address the congress contract address
*/
function initialCongress(address _congress) onlyOwner public {
require(!init);
require(_congress != address(0));
congress = _congress;
init = true;
}
/**
* @dev set a Congress contract address for this token
* must change this address by the last congress contract
*
* @param _congress address the congress contract address
*/
function changeCongress(address _congress) onlyCongress public {
require(_congress != address(0));
congress = _congress;
}
}
contract withdrawable is Ownable {
event ReceiveEther(address _from, uint256 _value);
event WithdrawEther(address _to, uint256 _value);
event WithdrawToken(address _token, address _to, uint256 _value);
/**
* @dev recording receiving ether from msn.sender
*/
function () payable public {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev withdraw,send ether to target
* @param _to is where the ether will be sent to
* _amount is the number of the ether
*/
function withdraw(address _to, uint _amount) public onlyOwner returns (bool) {
require(_to != address(0));
_to.transfer(_amount);
emit WithdrawEther(_to, _amount);
return true;
}
/**
* @dev withdraw tokens, send tokens to target
*
* @param _token the token address that will be withdraw
* @param _to is where the tokens will be sent to
* _value is the number of the token
*/
function withdrawToken(address _token, address _to, uint256 _value) public onlyOwner returns (bool) {
require(_to != address(0));
require(_token != address(0));
ERC20 tk = ERC20(_token);
tk.transfer(_to, _value);
emit WithdrawToken(_token, _to, _value);
return true;
}
/**
* @dev receive approval from an ERC20 token contract, and then gain the tokens,
* then take a record
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 the amounts of tokens to be sent
* @param _token address the ERC20 token address
* @param _extraData bytes the extra data for the record
*/
// function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public {
// require(_token != address(0));
// require(_from != address(0));
// ERC20 tk = ERC20(_token);
// require(tk.transferFrom(_from, this, _value));
// emit ReceiveDeposit(_from, _value, _token, _extraData);
// }
}
contract Destructible is Ownable {
function Destructible() public payable { }
/**
* @dev Transfers the current balance to the owner and terminates the contract.
*/
function destroy() onlyOwner public {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) onlyOwner public {
selfdestruct(_recipient);
}
}
contract TokenDestructible is Ownable {
function TokenDestructible() public payable { }
/**
* @notice Terminate contract and refund to owner
* @param tokens List of addresses of ERC20 or ERC20Basic token contracts to
refund.
* @notice The called token contracts could try to re-enter this contract. Only
supply token contracts you trust.
*/
function destroy(address[] tokens) onlyOwner public {
// Transfer tokens to owner
for (uint256 i = 0; i < tokens.length; i++) {
ERC20Basic token = ERC20Basic(tokens[i]);
uint256 balance = token.balanceOf(this);
token.transfer(owner, balance);
}
// Transfer Eth to owner and terminate contract
selfdestruct(owner);
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract OwnerContract is Claimable {
Claimable public ownedContract;
address internal origOwner;
/**
* @dev bind a contract as its owner
*
* @param _contract the contract address that will be binded by this Owner Contract
*/
function bindContract(address _contract) onlyOwner public returns (bool) {
require(_contract != address(0));
ownedContract = Claimable(_contract);
origOwner = ownedContract.owner();
// take ownership of the owned contract
ownedContract.claimOwnership();
return true;
}
/**
* @dev change the owner of the contract from this contract address to the original one.
*
*/
function transferOwnershipBack() onlyOwner public {
ownedContract.transferOwnership(origOwner);
ownedContract = Claimable(address(0));
origOwner = address(0);
}
/**
* @dev change the owner of the contract from this contract address to another one.
*
* @param _nextOwner the contract address that will be next Owner of the original Contract
*/
function changeOwnershipto(address _nextOwner) onlyOwner public {
ownedContract.transferOwnership(_nextOwner);
ownedContract = Claimable(address(0));
origOwner = address(0);
}
}
contract DepositWithdraw is Claimable, withdrawable {
using SafeMath for uint256;
/**
* transaction record
*/
struct TransferRecord {
uint256 timeStamp;
address account;
uint256 value;
}
/**
* accumulated transferring amount record
*/
struct accumulatedRecord {
uint256 mul;
uint256 count;
uint256 value;
}
TransferRecord[] deposRecs; // record all the deposit tx data
TransferRecord[] withdrRecs; // record all the withdraw tx data
accumulatedRecord dayWithdrawRec; // accumulated amount record for one day
accumulatedRecord monthWithdrawRec; // accumulated amount record for one month
address wallet; // the binded withdraw address
event ReceiveDeposit(address _from, uint256 _value, address _token, bytes _extraData);
/**
* @dev constructor of the DepositWithdraw contract
* @param _wallet the binded wallet address to this depositwithdraw contract
*/
constructor(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
}
/**
* @dev set the default wallet address
* @param _wallet the default wallet address binded to this deposit contract
*/
function setWithdrawWallet(address _wallet) onlyOwner public returns (bool) {
require(_wallet != address(0));
wallet = _wallet;
return true;
}
/**
* @dev util function to change bytes data to bytes32 data
* @param _data the bytes data to be converted
*/
function bytesToBytes32(bytes _data) public pure returns (bytes32 result) {
assembly {
result := mload(add(_data, 32))
}
}
/**
* @dev receive approval from an ERC20 token contract, take a record
*
* @param _from address The address which you want to send tokens from
* @param _value uint256 the amounts of tokens to be sent
* @param _token address the ERC20 token address
* @param _extraData bytes the extra data for the record
*/
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) onlyOwner public {
require(_token != address(0));
require(_from != address(0));
ERC20 tk = ERC20(_token);
require(tk.transferFrom(_from, this, _value));
bytes32 timestamp = bytesToBytes32(_extraData);
deposRecs.push(TransferRecord(uint256(timestamp), _from, _value));
emit ReceiveDeposit(_from, _value, _token, _extraData);
}
/**
* @dev withdraw tokens, send tokens to target
*
* @param _token the token address that will be withdraw
* @param _params the limitation parameters for withdraw
* @param _time the timstamp of the withdraw time
* @param _to is where the tokens will be sent to
* _value is the number of the token
* _fee is the amount of the transferring costs
* _tokenReturn is the address that return back the tokens of the _fee
*/
function withdrawToken(address _token, address _params, uint256 _time, address _to, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) {
require(_to != address(0));
require(_token != address(0));
require(_value > _fee);
// require(_tokenReturn != address(0));
DRCWalletMgrParams params = DRCWalletMgrParams(_params);
require(_value <= params.singleWithdrawMax());
require(_value >= params.singleWithdrawMin());
uint256 daysCount = _time.div(86400); // one day of seconds
if (daysCount <= dayWithdrawRec.mul) {
dayWithdrawRec.count = dayWithdrawRec.count.add(1);
dayWithdrawRec.value = dayWithdrawRec.value.add(_value);
require(dayWithdrawRec.count <= params.dayWithdrawCount());
require(dayWithdrawRec.value <= params.dayWithdraw());
} else {
dayWithdrawRec.mul = daysCount;
dayWithdrawRec.count = 1;
dayWithdrawRec.value = _value;
}
uint256 monthsCount = _time.div(86400 * 30);
if (monthsCount <= monthWithdrawRec.mul) {
monthWithdrawRec.count = monthWithdrawRec.count.add(1);
monthWithdrawRec.value = monthWithdrawRec.value.add(_value);
require(monthWithdrawRec.value <= params.monthWithdraw());
} else {
monthWithdrawRec.mul = monthsCount;
monthWithdrawRec.count = 1;
monthWithdrawRec.value = _value;
}
ERC20 tk = ERC20(_token);
uint256 realAmount = _value.sub(_fee);
require(tk.transfer(_to, realAmount));
if (_tokenReturn != address(0) && _fee > 0) {
require(tk.transfer(_tokenReturn, _fee));
}
withdrRecs.push(TransferRecord(_time, _to, realAmount));
emit WithdrawToken(_token, _to, realAmount);
return true;
}
/**
* @dev withdraw tokens, send tokens to target default wallet
*
* @param _token the token address that will be withdraw
* @param _params the limitation parameters for withdraw
* @param _time the timestamp occur the withdraw record
* @param _value is the number of the token
* _fee is the amount of the transferring costs
* —tokenReturn is the address that return back the tokens of the _fee
*/
function withdrawTokenToDefault(address _token, address _params, uint256 _time, uint256 _value, uint256 _fee, address _tokenReturn) public onlyOwner returns (bool) {
return withdrawToken(_token, _params, _time, wallet, _value, _fee, _tokenReturn);
}
/**
* @dev get the Deposit records number
*
*/
function getDepositNum() public view returns (uint256) {
return deposRecs.length;
}
/**
* @dev get the one of the Deposit records
*
* @param _ind the deposit record index
*/
function getOneDepositRec(uint256 _ind) public view returns (uint256, address, uint256) {
require(_ind < deposRecs.length);
return (deposRecs[_ind].timeStamp, deposRecs[_ind].account, deposRecs[_ind].value);
}
/**
* @dev get the withdraw records number
*
*/
function getWithdrawNum() public view returns (uint256) {
return withdrRecs.length;
}
/**
* @dev get the one of the withdraw records
*
* @param _ind the withdraw record index
*/
function getOneWithdrawRec(uint256 _ind) public view returns (uint256, address, uint256) {
require(_ind < withdrRecs.length);
return (withdrRecs[_ind].timeStamp, withdrRecs[_ind].account, withdrRecs[_ind].value);
}
}
contract DRCWalletManager is OwnerContract, withdrawable, Destructible, TokenDestructible {
using SafeMath for uint256;
/**
* withdraw wallet description
*/
struct WithdrawWallet {
bytes32 name;
address walletAddr;
}
/**
* Deposit data storage
*/
struct DepositRepository {
// uint256 balance;
uint256 frozen;
WithdrawWallet[] withdrawWallets;
// mapping (bytes32 => address) withdrawWallets;
}
mapping (address => DepositRepository) depositRepos;
mapping (address => address) walletDeposits;
mapping (address => bool) public frozenDeposits;
ERC20 public tk; // the token will be managed
DRCWalletMgrParams params; // the parameters that the management needs
event CreateDepositAddress(address indexed _wallet, address _deposit);
event FrozenTokens(address indexed _deposit, uint256 _value);
event ChangeDefaultWallet(address indexed _oldWallet, address _newWallet);
/**
* @dev withdraw tokens, send tokens to target default wallet
*
* @param _token the token address that will be withdraw
* @param _walletParams the wallet management parameters
*/
function bindToken(address _token, address _walletParams) onlyOwner public returns (bool) {
require(_token != address(0));
require(_walletParams != address(0));
tk = ERC20(_token);
params = DRCWalletMgrParams(_walletParams);
return true;
}
/**
* @dev create deposit contract address for the default withdraw wallet
*
* @param _wallet the binded default withdraw wallet address
*/
function createDepositContract(address _wallet) onlyOwner public returns (address) {
require(_wallet != address(0));
DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit
address _deposit = address(deposWithdr);
walletDeposits[_wallet] = _deposit;
WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets;
withdrawWalletList.push(WithdrawWallet("default wallet", _wallet));
// depositRepos[_deposit].balance = 0;
depositRepos[_deposit].frozen = 0;
emit CreateDepositAddress(_wallet, address(deposWithdr));
return deposWithdr;
}
/**
* @dev get deposit contract address by using the default withdraw wallet
*
* @param _wallet the binded default withdraw wallet address
*/
function getDepositAddress(address _wallet) onlyOwner public view returns (address) {
require(_wallet != address(0));
address deposit = walletDeposits[_wallet];
return deposit;
}
/**
* @dev get deposit balance and frozen amount by using the deposit address
*
* @param _deposit the deposit contract address
*/
function getDepositInfo(address _deposit) onlyOwner public view returns (uint256, uint256) {
require(_deposit != address(0));
uint256 _balance = tk.balanceOf(_deposit);
uint256 frozenAmount = depositRepos[_deposit].frozen;
// depositRepos[_deposit].balance = _balance;
return (_balance, frozenAmount);
}
/**
* @dev get the number of withdraw wallet addresses bindig to the deposit contract address
*
* @param _deposit the deposit contract address
*/
function getDepositWithdrawCount(address _deposit) onlyOwner public view returns (uint) {
require(_deposit != address(0));
WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets;
uint len = withdrawWalletList.length;
return len;
}
/**
* @dev get the withdraw wallet addresses list binding to the deposit contract address
*
* @param _deposit the deposit contract address
* @param _indices the array of indices of the withdraw wallets
*/
function getDepositWithdrawList(address _deposit, uint[] _indices) onlyOwner public view returns (bytes32[], address[]) {
require(_indices.length != 0);
bytes32[] memory names = new bytes32[](_indices.length);
address[] memory wallets = new address[](_indices.length);
for (uint i = 0; i < _indices.length; i = i.add(1)) {
WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]];
names[i] = wallet.name;
wallets[i] = wallet.walletAddr;
}
return (names, wallets);
}
/**
* @dev change the default withdraw wallet address binding to the deposit contract address
*
* @param _oldWallet the previous default withdraw wallet
* @param _newWallet the new default withdraw wallet
*/
function changeDefaultWithdraw(address _oldWallet, address _newWallet) onlyOwner public returns (bool) {
require(_newWallet != address(0));
address deposit = walletDeposits[_oldWallet];
DepositWithdraw deposWithdr = DepositWithdraw(deposit);
require(deposWithdr.setWithdrawWallet(_newWallet));
WithdrawWallet[] storage withdrawWalletList = depositRepos[deposit].withdrawWallets;
withdrawWalletList[0].walletAddr = _newWallet;
emit ChangeDefaultWallet(_oldWallet, _newWallet);
return true;
}
/**
* @dev freeze the tokens in the deposit address
*
* @param _deposit the deposit address
* @param _value the amount of tokens need to be frozen
*/
function freezeTokens(address _deposit, uint256 _value) onlyOwner public returns (bool) {
require(_deposit != address(0));
frozenDeposits[_deposit] = true;
depositRepos[_deposit].frozen = _value;
emit FrozenTokens(_deposit, _value);
return true;
}
/**
* @dev withdraw the tokens from the deposit address with charge fee
*
* @param _deposit the deposit address
* @param _time the timestamp the withdraw occurs
* @param _value the amount of tokens need to be frozen
*/
function withdrawWithFee(address _deposit, uint256 _time, uint256 _value) onlyOwner public returns (bool) {
require(_deposit != address(0));
uint256 _balance = tk.balanceOf(_deposit);
require(_value <= _balance);
// depositRepos[_deposit].balance = _balance;
uint256 frozenAmount = depositRepos[_deposit].frozen;
require(_value <= _balance.sub(frozenAmount));
DepositWithdraw deposWithdr = DepositWithdraw(_deposit);
return (deposWithdr.withdrawTokenToDefault(address(tk), address(params), _time, _value, params.chargeFee(), params.chargeFeePool()));
}
/**
* @dev check if the wallet name is not matching the expected wallet address
*
* @param _deposit the deposit address
* @param _name the withdraw wallet name
* @param _to the withdraw wallet address
*/
function checkWithdrawAddress(address _deposit, bytes32 _name, address _to) public view returns (bool, bool) {
uint len = depositRepos[_deposit].withdrawWallets.length;
for (uint i = 0; i < len; i = i.add(1)) {
WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[i];
if (_name == wallet.name) {
return(true, (_to == wallet.walletAddr));
}
}
return (false, true);
}
/**
* @dev withdraw tokens, send tokens to target withdraw wallet
*
* @param _deposit the deposit address that will be withdraw from
* @param _time the timestamp occur the withdraw record
* @param _name the withdraw address alias name to verify
* @param _to the address the token will be transfer to
* @param _value the token transferred value
* @param _check if we will check the value is valid or meet the limit condition
*/
function withdrawWithFee(address _deposit,
uint256 _time,
bytes32 _name,
address _to,
uint256 _value,
bool _check) onlyOwner public returns (bool) {
require(_deposit != address(0));
require(_to != address(0));
uint256 _balance = tk.balanceOf(_deposit);
if (_check) {
require(_value <= _balance);
}
uint256 available = _balance.sub(depositRepos[_deposit].frozen);
if (_check) {
require(_value <= available);
}
bool exist;
bool correct;
WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets;
(exist, correct) = checkWithdrawAddress(_deposit, _name, _to);
if(!exist) {
withdrawWalletList.push(WithdrawWallet(_name, _to));
} else if(!correct) {
return false;
}
if (!_check && _value > available) {
tk.transfer(_deposit, _value.sub(available));
// _value = _value.sub(available);
}
DepositWithdraw deposWithdr = DepositWithdraw(_deposit);
return (deposWithdr.withdrawToken(address(tk), address(params), _time, _to, _value, params.chargeFee(), params.chargeFeePool()));
}
}
contract DRCWalletMgrParams is Claimable, Autonomy, Destructible {
uint256 public singleWithdrawMin; // min value of single withdraw
uint256 public singleWithdrawMax; // Max value of single withdraw
uint256 public dayWithdraw; // Max value of one day of withdraw
uint256 public monthWithdraw; // Max value of one month of withdraw
uint256 public dayWithdrawCount; // Max number of withdraw counting
uint256 public chargeFee; // the charge fee for withdraw
address public chargeFeePool; // the address that will get the returned charge fees.
function initialSingleWithdrawMax(uint256 _value) onlyOwner public {
require(!init);
singleWithdrawMax = _value;
}
function initialSingleWithdrawMin(uint256 _value) onlyOwner public {
require(!init);
singleWithdrawMin = _value;
}
function initialDayWithdraw(uint256 _value) onlyOwner public {
require(!init);
dayWithdraw = _value;
}
function initialDayWithdrawCount(uint256 _count) onlyOwner public {
require(!init);
dayWithdrawCount = _count;
}
function initialMonthWithdraw(uint256 _value) onlyOwner public {
require(!init);
monthWithdraw = _value;
}
function initialChargeFee(uint256 _value) onlyOwner public {
require(!init);
chargeFee = _value;
}
function initialChargeFeePool(address _pool) onlyOwner public {
require(!init);
chargeFeePool = _pool;
}
function setSingleWithdrawMax(uint256 _value) onlyCongress public {
singleWithdrawMax = _value;
}
function setSingleWithdrawMin(uint256 _value) onlyCongress public {
singleWithdrawMin = _value;
}
function setDayWithdraw(uint256 _value) onlyCongress public {
dayWithdraw = _value;
}
function setDayWithdrawCount(uint256 _count) onlyCongress public {
dayWithdrawCount = _count;
}
function setMonthWithdraw(uint256 _value) onlyCongress public {
monthWithdraw = _value;
}
function setChargeFee(uint256 _value) onlyCongress public {
chargeFee = _value;
}
function setChargeFeePool(address _pool) onlyCongress public {
chargeFeePool = _pool;
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
} | accumulated amount record for one month
| accumulatedRecord monthWithdrawRec; | 9,845,213 | [
1,
8981,
5283,
690,
3844,
1409,
364,
1245,
3138,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24893,
2115,
3138,
1190,
9446,
5650,
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 FR_ADJ.SOL
//
// (c) Koziev Elijah
// Solarix Intellectronix project http://www.solarix.ru
//
// Content:
// Лексикон - определения прилагательных для французского раздела Словаря.
// -----------------------------------------------------------------------------
//
// CD->07.05.2006
// LC->07.05.2011
// --------------
#include "sg_defs.h"
automat sg
{
// ***********************************************************
paradigm acquisitif : FR_ADJ for "(.+)IF"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // acquisitif - acquisitifs
FR_GENRE:FEMININE FR_NOMBRE { "%-1%+VE" "%-1%+VES" } // acquisitive - acquisitives
}
paradigm acrimonieux : FR_ADJ for "(.+)eux"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "" } // acrimonieux - acrimonieux
FR_GENRE:FEMININE FR_NOMBRE { "%-1%+SE" "%-1%+SES" } // acrimonieuse - acrimonieuses
}
paradigm constructeur : FR_ADJ for "(.+)TEUR"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // constructeur constructeurs
FR_GENRE:FEMININE FR_NOMBRE { "%-3%+RICE" "%-3%+RICES" } // constructrice constructrices
}
paradigm grondeur : FR_ADJ for "(.+)EUR"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // grondeur-grondeurs
FR_GENRE:FEMININE FR_NOMBRE { "%-1%+SE" "%-1%+SES" } // grondeuse-grondeuses
}
paradigm acromial : FR_ADJ for "(.+)al"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%-1%+UX" } // acromial - acromiaux
FR_GENRE:FEMININE FR_NOMBRE { "%+E" "%+ES" } // acromiale - acromiales
}
paradigm actuariel,diluvien : FR_ADJ for "(.+)e[lnt]"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // actuariel - actuariels, diluvien-diluviens, guilleret-guillerets
FR_GENRE:FEMININE FR_NOMBRE { "%D%+E" "%D%+ES" } // actuarielle - actuarielles, diluvienne-diluviennes, guillerette-guillerettes
}
paradigm abscons : FR_ADJ for "(.+)S"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "" } // abscons - abscons
FR_GENRE:FEMININE FR_NOMBRE { "%+E" "%+ES" } // absconse - absconses
}
paradigm adamantin : FR_ADJ for "(.+)\\@c"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // adamantin - adamantins
FR_GENRE:FEMININE FR_NOMBRE { "%+E" "%+ES" } // adamantine - adamantines
}
paradigm acuminé : FR_ADJ for "(.+)É"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // acuminé - acuminés
FR_GENRE:FEMININE FR_NOMBRE { "%+E" "%+ES" } // acuminée - acuminées
}
paradigm inouï : FR_ADJ for "(.+)ï"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // inouï - inouïs
FR_GENRE:FEMININE FR_NOMBRE { "%+E" "%+ES" } // inouïe - inouïes
}
paradigm acidophile : FR_ADJ for "(.+)[EA]"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // acidophile - acidophiles
FR_GENRE:FEMININE FR_NOMBRE { "" "%+S" } // acidophile - acidophiles
}
paradigm coi,rigolo : FR_ADJ for "(.+)[IO]"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } // coi-cois, rigolo-rigolos
FR_GENRE:FEMININE FR_NOMBRE { "%+TE" "%+TES" } // coite-coites, rigolote-rigolotes
}
paradigm ventru : FR_ADJ for "(.+)U"
{
FR_GENRE:MASCULINE FR_NOMBRE { "" "%+s" } // ventru - ventrus
FR_GENRE:FEMININE FR_NOMBRE { "%+e" "%+es" } // ventrue - ventrues
}
// ***********************************************************
#define fradj(Word) \
#begin
entry Word : FR_ADJ
{
paradigm auto
}
#end
entry TOUT : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { "TOUT" "TOUS" }
FR_GENRE:FEMININE FR_NOMBRE { "TOUTE" "TOUTES" }
}
entry NOUVEAU : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { NOUVEAU nouveaux }
FR_GENRE:MASCULINE { NOUVEL }
FR_GENRE:FEMININE FR_NOMBRE { NOUVELLE nouvelles }
}
entry beau : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { beau beaux }
FR_GENRE:MASCULINE { bel }
FR_GENRE:FEMININE FR_NOMBRE { belle belles }
}
entry bon : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { bon bons }
FR_GENRE:FEMININE FR_NOMBRE { bonne bonnes }
}
entry bas : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { bas bas }
FR_GENRE:FEMININE FR_NOMBRE { basse basses }
}
entry blanc : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { blanc blancs }
FR_GENRE:FEMININE FR_NOMBRE { blanche blanches }
}
entry long : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { long longs }
FR_GENRE:FEMININE FR_NOMBRE { longue longues }
}
entry vieux : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { vieux vieux }
FR_GENRE:MASCULINE { vieil }
FR_GENRE:FEMININE FR_NOMBRE { vieille vieilles }
}
entry premier : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { premier premiers }
FR_GENRE:MASCULINE FR_NOMBRE:SINGULIER { "1er" }
FR_GENRE:FEMININE FR_NOMBRE { première premières }
FR_GENRE:FEMININE FR_NOMBRE:SINGULIER { "1re" }
}
entry second : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { second seconds }
FR_GENRE:MASCULINE FR_NOMBRE { deuxième deuxième }
FR_GENRE:MASCULINE FR_NOMBRE:SINGULIER { "2d" }
FR_GENRE:MASCULINE FR_NOMBRE:SINGULIER { "2e" }
FR_GENRE:MASCULINE FR_NOMBRE:SINGULIER { "2ème" }
FR_GENRE:MASCULINE FR_NOMBRE:SINGULIER { "IIème" }
FR_GENRE:FEMININE FR_NOMBRE { seconde secondes }
FR_GENRE:FEMININE FR_NOMBRE:SINGULIER { "2de" }
FR_GENRE:FEMININE FR_NOMBRE:SINGULIER { "2e" }
FR_GENRE:FEMININE FR_NOMBRE:SINGULIER { "2ème" }
FR_GENRE:FEMININE FR_NOMBRE:SINGULIER { "IIème" }
}
fradj( français )
fradj( "abaissable" )
fradj( "abbatial" )
fradj( "abdominal" )
fradj( "abducteur" )
fradj( "abiotique" )
fradj( "abjecte" )
fradj( "abondante" )
fradj( "abordable" )
fradj( "abordé" )
fradj( "abracadabrant" )
fradj( "abritée" )
fradj( "abrogatif" )
fradj( "abrogatoire" )
fradj( "abrogeable" )
fradj( "abscons" )
fradj( "absolutiste" )
fradj( "abstrus" )
fradj( "abusif" )
fradj( "abyssinien" )
fradj( "acadien" )
fradj( "académique" )
fradj( "acariâtre" )
fradj( "accaparant" )
fradj( "accentuée" )
fradj( "accepté" )
fradj( "accidentel" )
fradj( "accidentelle" )
fradj( "acclimatable" )
fradj( "accommodé" )
fradj( "accordable" )
fradj( "accort" )
fradj( "accorte" )
fradj( "accostable" )
fradj( "accueillante" )
fradj( "accusateur" )
fradj( "acerbe" )
fradj( "achalandé" )
fradj( "achetable" )
fradj( "achromique" )
fradj( "aciculaire" )
fradj( "acquittable" )
fradj( "acrimonieux" )
fradj( "acrobatique" )
fradj( "actuel" )
fradj( "actuelle" )
fradj( "acuminé" )
fradj( "acutangle" )
fradj( "acyclique" )
fradj( "acétique" )
fradj( "adamantin" )
fradj( "adaptatif" )
fradj( "additionnel" )
fradj( "additionnelle" )
fradj( "additionné" )
fradj( "adhésif" )
fradj( "adipeux" )
fradj( "adjacente" )
fradj( "adjectif" )
fradj( "adjuvante" )
fradj( "admirables" )
fradj( "admirateur" )
fradj( "admiratif" )
fradj( "adoptable" )
fradj( "adorables" )
fradj( "adroite" )
fradj( "adultérin" )
fradj( "adventice" )
fradj( "adventif" )
fradj( "adverse" )
fradj( "adynamique" )
fradj( "adénoïde" )
fradj( "adéquat" )
fradj( "affectueux" )
fradj( "affin" )
fradj( "affirmatif" )
fradj( "afflictif" )
fradj( "affété" )
fradj( "agglutinant" )
fradj( "agissante" )
fradj( "agnathe" )
fradj( "agraire" )
fradj( "agressif" )
fradj( "agricole" )
fradj( "agronomique" )
fradj( "agrégatif" )
fradj( "ahanant" )
fradj( "aigrelet" )
fradj( "aigrelette" )
fradj( "ailé" )
fradj( "aimable" )
fradj( "aisé" )
fradj( "alambiqué" )
fradj( "alcalescent" )
fradj( "alchimique" )
fradj( "alezan" )
fradj( "algorithmique" )
fradj( "algébrique" )
fradj( "alimentaire" )
fradj( "alizé" )
fradj( "alliacé" )
fradj( "allochtone" )
fradj( "allopathe" )
fradj( "allotropique" )
fradj( "allouable" )
fradj( "allumeur" )
fradj( "alluré" )
fradj( "allusif" )
fradj( "alluviale" )
fradj( "allègre" )
fradj( "alléchant" )
fradj( "allégorique" )
fradj( "alogique" )
fradj( "alpestre" )
fradj( "alpin" )
fradj( "alternant" )
fradj( "alternatif" )
fradj( "altier" )
fradj( "altière" )
fradj( "altérable" )
fradj( "alvin" )
fradj( "alvéolaire" )
fradj( "aléatoire" )
fradj( "ambiant" )
fradj( "ambivalent" )
fradj( "ambulatoire" )
fradj( "amendable" )
fradj( "amical" )
fradj( "amiral" )
fradj( "ammoniac" )
fradj( "amnistiable" )
fradj( "amorphe" )
fradj( "amortissable" )
fradj( "amovible" )
fradj( "amphibologique" )
fradj( "amphigourique" )
fradj( "ampliatif" )
fradj( "améliorable" )
fradj( "aménageable" )
fradj( "anachorétique" )
fradj( "anachronique" )
fradj( "analgésique" )
fradj( "anallergique" )
fradj( "analogique" )
fradj( "analogues" )
fradj( "analysable" )
fradj( "analytique" )
fradj( "anaphylactique" )
fradj( "anarchique" )
fradj( "anatomique" )
fradj( "ancestral" )
fradj( "androïde" )
fradj( "anecdotique" )
fradj( "anglo-saxon" )
fradj( "anguleux" )
fradj( "anhydre" )
fradj( "animalier" )
fradj( "ankylosé" )
fradj( "annale" )
fradj( "annuelle" )
fradj( "annulable" )
fradj( "anodin" )
fradj( "anodine" )
fradj( "anomal" )
fradj( "anorexique" )
fradj( "antagonique" )
fradj( "antalgique" )
fradj( "antenaise" )
fradj( "anthropologique" )
fradj( "anthropomorphe" )
fradj( "anthropomorphique" )
fradj( "anthropométrique" )
fradj( "anthropoïde" )
fradj( "anticonceptionnel" )
fradj( "anticonstitutionnel" )
fradj( "anticonstitutionnelle" )
fradj( "antidépresseur" )
fradj( "antinational" )
fradj( "antinomique" )
fradj( "antioxydant" )
fradj( "antipaludique" )
fradj( "antipaludéen" )
fradj( "antipathique" )
fradj( "antiphlogistique" )
fradj( "antipyrétique" )
fradj( "antireligieux" )
fradj( "antirouille" )
fradj( "antiroulis" )
fradj( "antiseptique" )
fradj( "antispasmodique" )
fradj( "antithétique" )
fradj( "antédiluvien" )
fradj( "antérieur" )
fradj( "anxieux" )
fradj( "apathique" )
fradj( "apatride" )
fradj( "apercevable" )
fradj( "aphone" )
fradj( "apocalyptique" )
fradj( "apodictique" )
fradj( "apoplectique" )
fradj( "apprivoisable" )
fradj( "apprivoisé" )
fradj( "approbatif" )
fradj( "approchable" )
fradj( "approchante" )
fradj( "approprié" )
fradj( "approuvable" )
fradj( "approximatif" )
fradj( "appréciatif" )
fradj( "appétissant" )
fradj( "apraxique" )
fradj( "apte" )
fradj( "aptère" )
fradj( "aquatique" )
fradj( "aqueux" )
fradj( "aquicole" )
fradj( "aquilin" )
fradj( "arachnéen" )
fradj( "araméen" )
fradj( "arborisé" )
fradj( "archangélique" )
fradj( "archaïque" )
fradj( "architectural" )
fradj( "archéen" )
fradj( "archéologique" )
fradj( "arctique" )
fradj( "ardente" )
fradj( "ardoisier" )
fradj( "ardu" )
fradj( "areligieux" )
fradj( "argileux" )
fradj( "aride" )
fradj( "aristocratique" )
fradj( "armoricain" )
fradj( "arrangeable" )
fradj( "arriéré" )
fradj( "arrosable" )
fradj( "arthritique" )
fradj( "artificiel" )
fradj( "artificieux" )
fradj( "artisanal" )
fradj( "aréique" )
fradj( "arénacé" )
fradj( "arénicole" )
fradj( "ascendants" )
fradj( "ascensionnel" )
fradj( "ascétique" )
fradj( "aseptique" )
fradj( "asiate" )
fradj( "asiatique" )
fradj( "assidu" )
fradj( "assidue" )
fradj( "assignable" )
fradj( "assimilable" )
fradj( "associatif" )
fradj( "assoiffé" )
fradj( "assurable" )
fradj( "asthmatique" )
fradj( "asthénique" )
fradj( "astral" )
fradj( "astronomique" )
fradj( "astucieux" )
fradj( "asymétrique" )
fradj( "asynchrone" )
fradj( "atavique" )
fradj( "atemporel" )
fradj( "athlétique" )
fradj( "atmosphérique" )
fradj( "atomique" )
fradj( "atonal" )
fradj( "atone" )
fradj( "atonique" )
fradj( "atrabilaire" )
fradj( "atroce" )
fradj( "attachant" )
fradj( "attaquable" )
fradj( "attenante" )
fradj( "attentatoire" )
fradj( "attentif" )
fradj( "attractif" )
fradj( "attrayant" )
fradj( "attribuable" )
fradj( "attributif" )
fradj( "atypique" )
fradj( "auburn" )
fradj( "audacieux" )
fradj( "auguste" )
fradj( "austère" )
fradj( "autarcique" )
fradj( "autobiographique" )
fradj( "autocratique" )
fradj( "autodestructeur" )
fradj( "autonomiste" )
fradj( "avant-dernier" )
fradj( "avaricieux" )
fradj( "avenante" )
fradj( "aventureux" )
fradj( "avenu" )
fradj( "avide" )
fradj( "avilissante" )
fradj( "avisé" )
fradj( "avouable" )
fradj( "avunculaire" )
fradj( "azotique" )
fradj( "azoïque" )
fradj( "aérien" )
fradj( "aéroporté" )
fradj( "babylonien" )
fradj( "bactérien" )
fradj( "bactériostatique" )
fradj( "bagarreur" )
fradj( "ballante" )
fradj( "balnéaire" )
fradj( "banal" )
fradj( "banale" )
fradj( "bancable" )
fradj( "bancaire" )
fradj( "bancale" )
fradj( "barbaresque" )
fradj( "barbifiant" )
fradj( "barométrique" )
fradj( "basique" )
fradj( "bateleux" )
fradj( "baveux" )
fradj( "belliciste" )
fradj( "belligérant" )
fradj( "bellâtre" )
fradj( "benoît" )
fradj( "benzénique" )
fradj( "berbère" )
fradj( "berceur" )
fradj( "bestiale" )
fradj( "bibliothécaire" )
fradj( "biblique" )
fradj( "bicolore" )
fradj( "bien-fondé" )
fradj( "bienfaisant" )
fradj( "bienfaisante" )
fradj( "biennal" )
fradj( "bienséant" )
fradj( "bienveillant" )
fradj( "bienveillante" )
fradj( "bienvenu" )
fradj( "bifide" )
fradj( "bijectif" )
fradj( "bilatéral" )
fradj( "bileux" )
fradj( "bimoteur" )
fradj( "binaire" )
fradj( "biodégradable" )
fradj( "biologique" )
fradj( "biotique" )
fradj( "bisannuel" )
fradj( "bisannuelle" )
fradj( "biscornu" )
fradj( "bisexué" )
fradj( "bitumeux" )
fradj( "biturbine" )
fradj( "biunivoque" )
fradj( "bizarroïde" )
fradj( "blafard" )
fradj( "blafarde" )
fradj( "blanchâtre" )
fradj( "blasphématoire" )
fradj( "blessante" )
fradj( "blet" )
fradj( "bleue" )
fradj( "bleuâtre" )
fradj( "blindée" )
fradj( "blondasse" )
fradj( "blondin" )
fradj( "blondinet" )
fradj( "blousant" )
fradj( "blâmable" )
fradj( "blême" )
fradj( "bocager" )
fradj( "bonasse" )
fradj( "booléen" )
fradj( "borné" )
fradj( "bornée" )
fradj( "boréal" )
fradj( "bossu" )
fradj( "boudiné" )
fradj( "bouillante" )
fradj( "boulevardier" )
fradj( "boulevardière" )
fradj( "boulot" )
fradj( "bourbeux" )
fradj( "bourbonien" )
fradj( "bourguignon" )
fradj( "bourratif" )
fradj( "bourrelé" )
fradj( "boursicoteur" )
fradj( "boutonneux" )
fradj( "brailleur" )
fradj( "branchu" )
fradj( "branlante" )
fradj( "brouillon" )
fradj( "broussailleux" )
fradj( "brownien" )
fradj( "broyeur" )
fradj( "bruineux" )
fradj( "brumeux" )
fradj( "brunâtre" )
fradj( "bruyant" )
fradj( "bruyante" )
fradj( "buccal" )
fradj( "budgétaire" )
fradj( "buissonneux" )
fradj( "bulbeux" )
fradj( "buraliste" )
fradj( "bureaucratique" )
fradj( "busqué" )
fradj( "busquée" )
fradj( "buvable" )
fradj( "buveur" )
fradj( "byzantin" )
fradj( "béante" )
fradj( "béchique" )
fradj( "bénigne" )
fradj( "bénéfique" )
fradj( "bénévole" )
fradj( "béotien" )
fradj( "bêtifiant" )
fradj( "bûcheur" )
fradj( "cabalistique" )
fradj( "cachée" )
fradj( "cadavéreux" )
fradj( "cadavérique" )
fradj( "caduc" )
fradj( "cafardeux" )
fradj( "cafouilleur" )
fradj( "cagneux" )
fradj( "caillouteux" )
fradj( "calamiteux" )
fradj( "calcifuge" )
fradj( "calculé" )
fradj( "calculée" )
fradj( "callipyge" )
fradj( "calmante" )
fradj( "calomnieux" )
fradj( "calotin" )
fradj( "cambiste" )
fradj( "cambodgien" )
fradj( "cambrien" )
fradj( "camus" )
fradj( "canadien" )
fradj( "cancérigène" )
fradj( "candide" )
fradj( "caniculaires" )
fradj( "capiteux" )
fradj( "capricant" )
fradj( "caprin" )
fradj( "captatif" )
fradj( "captieux" )
fradj( "carcéral" )
fradj( "caressante" )
fradj( "caricatural" )
fradj( "caritatif" )
fradj( "carnassier" )
fradj( "carrossable" )
fradj( "cartilagineux" )
fradj( "cartographique" )
fradj( "cascadeur" )
fradj( "cassante" )
fradj( "casuel" )
fradj( "catastrophique" )
fradj( "catégoriel" )
fradj( "catégorique" )
fradj( "cauteleux" )
fradj( "caverneux" )
fradj( "cendreux" )
fradj( "cessible" )
fradj( "chaleureux" )
fradj( "chamailleur" )
fradj( "champêtre" )
fradj( "chaotique" )
fradj( "chapelier" )
fradj( "charbonneux" )
fradj( "charcutier" )
fradj( "charentaise" )
fradj( "charmante" )
fradj( "charmants" )
fradj( "charmeur" )
fradj( "charnel" )
fradj( "charnelle" )
fradj( "charnu" )
fradj( "charnue" )
fradj( "charretier" )
fradj( "chaste" )
fradj( "chatouilleux" )
fradj( "chatoyante" )
fradj( "chenu" )
fradj( "chevaleresque" )
fradj( "chevalin" )
fradj( "chevelue" )
fradj( "chicanier" )
fradj( "chiffrable" )
fradj( "chimérique" )
fradj( "chipoteur" )
fradj( "chipoteux" )
fradj( "chocolat" )
fradj( "chthonien" )
fradj( "chérifien" )
fradj( "chérot" )
fradj( "chétif" )
fradj( "cinématographique" )
fradj( "cinéraire" )
fradj( "cinétique" )
fradj( "circonflexe" )
fradj( "circonspect" )
fradj( "circonstanciel" )
fradj( "cireux" )
fradj( "citadin" )
fradj( "civil" )
fradj( "civique" )
fradj( "clanique" )
fradj( "claudicant" )
fradj( "climatique" )
fradj( "climatérique" )
fradj( "clinicien" )
fradj( "clinorhombique" )
fradj( "clownesque" )
fradj( "cocardier" )
fradj( "cocasse" )
fradj( "coccygien" )
fradj( "codicillaire" )
fradj( "codificateur" )
fradj( "coeliaque" )
fradj( "coercible" )
fradj( "coercitif" )
fradj( "cohésif" )
fradj( "collectif" )
fradj( "colloïdal" )
fradj( "colloïdale" )
fradj( "collégial" )
fradj( "colonisateur" )
fradj( "colorants" )
fradj( "colossal" )
fradj( "combatif" )
fradj( "combinable" )
fradj( "commercialisable" )
fradj( "comminatoire" )
fradj( "communautaire" )
fradj( "communicateur" )
fradj( "communicatif" )
fradj( "commémoratif" )
fradj( "comparables" )
fradj( "compendieux" )
fradj( "compensable" )
fradj( "compensatoire" )
fradj( "complaisante" )
fradj( "comportemental" )
fradj( "comportementale" )
fradj( "compressible" )
fradj( "comprimable" )
fradj( "compréhensif" )
fradj( "compulsif" )
fradj( "compétitif" )
fradj( "comédien" )
fradj( "concasseur" )
fradj( "concentrique" )
fradj( "conceptuel" )
fradj( "conceptuelle" )
fradj( "concessif" )
fradj( "concevable" )
fradj( "conchylien" )
fradj( "conciliable" )
fradj( "concis" )
fradj( "concupiscent" )
fradj( "concurrente" )
fradj( "concurrentiel" )
fradj( "condamnable" )
fradj( "condensable" )
fradj( "condescendante" )
fradj( "conductible" )
fradj( "confessionnel" )
fradj( "confiante" )
fradj( "confidentiel" )
fradj( "confidentielle" )
fradj( "conflictuel" )
fradj( "confortable" )
fradj( "confraternel" )
fradj( "confus" )
fradj( "confédéral" )
fradj( "congru" )
fradj( "congédiable" )
fradj( "congénère" )
fradj( "conjoncturel" )
fradj( "conjoncturelle" )
fradj( "conjugal" )
fradj( "connaissable" )
fradj( "connexe" )
fradj( "consanguin" )
fradj( "consciente" )
fradj( "conscrit" )
fradj( "considérables" )
fradj( "consistante" )
fradj( "consolant" )
fradj( "consommable" )
fradj( "consomptible" )
fradj( "constants" )
fradj( "constitutionnel" )
fradj( "constructif" )
fradj( "constructeur" )
fradj( "consubstantiel" )
fradj( "consultable" )
fradj( "consécutif" )
fradj( "contemplatif" )
fradj( "contentif" )
fradj( "contestable" )
fradj( "continu" )
fradj( "continuel" )
fradj( "continuelle" )
fradj( "contondant" )
fradj( "contractuel" )
fradj( "contradictoire" )
fradj( "contrariante" )
fradj( "contrasté" )
fradj( "contrit" )
fradj( "controversable" )
fradj( "controversé" )
fradj( "contrôlable" )
fradj( "convaincant" )
fradj( "convenable" )
fradj( "conventuel" )
fradj( "convenue" )
fradj( "conversationnel" )
fradj( "conversationnelle" )
fradj( "convexe" )
fradj( "convulsif" )
fradj( "coordinateur" )
fradj( "coordonnateur" )
fradj( "copieux" )
fradj( "coranique" )
fradj( "corbin" )
fradj( "cordiale" )
fradj( "coriace" )
fradj( "cornu" )
fradj( "corporel" )
fradj( "corpulente" )
fradj( "correctif" )
fradj( "corrects" )
fradj( "corrupteur" )
fradj( "corruptible" )
fradj( "cosmique" )
fradj( "cosmographique" )
fradj( "cosmopolites" )
fradj( "cossu" )
fradj( "cotonneux" )
fradj( "couperosé" )
fradj( "courbatu" )
fradj( "courbé" )
fradj( "courte" )
fradj( "courtois" )
fradj( "courtoise" )
fradj( "coutumière" )
fradj( "coxal" )
fradj( "coûteux" )
fradj( "craintif" )
fradj( "crapuleux" )
fradj( "crasseux" )
fradj( "crayeux" )
fradj( "criard" )
fradj( "criarde" )
fradj( "crispant" )
fradj( "crochu" )
fradj( "croissante" )
fradj( "croupissante" )
fradj( "croustillante" )
fradj( "croyable" )
fradj( "crucial" )
fradj( "cruel" )
fradj( "cryptique" )
fradj( "créatif" )
fradj( "crédule" )
fradj( "crémeux" )
fradj( "crépu" )
fradj( "crépusculaire" )
fradj( "crétinisant" )
fradj( "culinaire" )
fradj( "cultivable" )
fradj( "cultuel" )
fradj( "culturel" )
fradj( "cumulatif" )
fradj( "cupide" )
fradj( "cuprifère" )
fradj( "cuprique" )
fradj( "curatif" )
fradj( "cursif" )
fradj( "curviligne" )
fradj( "cutané" )
fradj( "cyanhydrique" )
fradj( "cyclique" )
fradj( "cyclonal" )
fradj( "cyclonique" )
fradj( "cyclopéen" )
fradj( "cyclopéenne" )
fradj( "cyclothymique" )
fradj( "cycloïdal" )
fradj( "cylindrique" )
fradj( "cytologique" )
fradj( "câlin" )
fradj( "célestes" )
fradj( "cénobitique" )
fradj( "céruléen" )
fradj( "céruléenne" )
fradj( "cérébrale" )
fradj( "cérémonieux" )
fradj( "damné" )
fradj( "dangereux" )
fradj( "dantesque" )
fradj( "daubeur" )
fradj( "demi-fin" )
fradj( "dentelé" )
fradj( "dermique" )
fradj( "descendants" )
fradj( "descriptif" )
fradj( "despotique" )
fradj( "destructif" )
fradj( "devinable" )
fradj( "diabolique" )
fradj( "diachronique" )
fradj( "diacritique" )
fradj( "dialectal" )
fradj( "dialogique" )
fradj( "dialypétale" )
fradj( "diaphane" )
fradj( "diastasique" )
fradj( "dichotomique" )
fradj( "dictatorial" )
fradj( "didactique" )
fradj( "diffamatoire" )
fradj( "difficile" )
fradj( "diffus" )
fradj( "diffusant" )
fradj( "différenciateur" )
fradj( "digestible" )
fradj( "digital" )
fradj( "digne" )
fradj( "digérable" )
fradj( "dilapidateur" )
fradj( "dilatable" )
fradj( "dilatante" )
fradj( "dilatoire" )
fradj( "diligent" )
fradj( "diluvial" )
fradj( "diluvien" )
fradj( "dionysiaque" )
fradj( "diplomatique" )
fradj( "directe" )
fradj( "directif" )
fradj( "directionnel" )
fradj( "directionnelle" )
fradj( "dirigeable" )
fradj( "discernable" )
fradj( "discourtois" )
fradj( "discourtoise" )
fradj( "discret" )
fradj( "discriminatoire" )
fradj( "discrétionnaire" )
fradj( "discursif" )
fradj( "discutable" )
fradj( "disert" )
fradj( "disgracieux" )
fradj( "disgracié" )
fradj( "dispendieux" )
fradj( "dispos" )
fradj( "disposé" )
fradj( "disproportionné" )
fradj( "dissemblable" )
fradj( "dissipateur" )
fradj( "dissociable" )
fradj( "dissolu" )
fradj( "dissonante" )
fradj( "distincte" )
fradj( "distinctif" )
fradj( "distincts" )
fradj( "distinguable" )
fradj( "dithyrambique" )
fradj( "divergentes" )
fradj( "diversiforme" )
fradj( "divinateur" )
fradj( "divins" )
fradj( "dodu" )
fradj( "dodue" )
fradj( "dodécaphonique" )
fradj( "dodécasyllabe" )
fradj( "dommageable" )
fradj( "dormeur" )
fradj( "doseur" )
fradj( "doubleau" )
fradj( "douceâtre" )
fradj( "douloureux" )
fradj( "douteux" )
fradj( "draconien" )
fradj( "drue" )
fradj( "dubitatif" )
fradj( "duveteux" )
fradj( "débonnaire" )
fradj( "débordante" )
fradj( "déchiffrable" )
fradj( "déchiré" )
fradj( "décidable" )
fradj( "décisif" )
fradj( "déclamatoire" )
fradj( "déclaratif" )
fradj( "décoratif" )
fradj( "dédaléen" )
fradj( "déductif" )
fradj( "défavorable" )
fradj( "défectueux" )
fradj( "défendable" )
fradj( "défiante" )
fradj( "définissable" )
fradj( "dégagé" )
fradj( "délibérée" )
fradj( "délicat" )
fradj( "délicieux" )
fradj( "délictueux" )
fradj( "déliquescent" )
fradj( "déliquescente" )
fradj( "délirant" )
fradj( "déloyal" )
fradj( "déloyale" )
fradj( "délébile" )
fradj( "délétère" )
fradj( "démontrable" )
fradj( "dénombrable" )
fradj( "dénué" )
fradj( "déplaisante" )
fradj( "déplumé" )
fradj( "dépravé" )
fradj( "dépressif" )
fradj( "dépréciatif" )
fradj( "déraisonnable" )
fradj( "dérisoire" )
fradj( "désagréable" )
fradj( "désapprobateur" )
fradj( "désavantageux" )
fradj( "désertique" )
fradj( "déshonnête" )
fradj( "désinfectant" )
fradj( "désossé" )
fradj( "désuet" )
fradj( "détachable" )
fradj( "détaché" )
fradj( "détectable" )
fradj( "déterminable" )
fradj( "déterminante" )
fradj( "détersif" )
fradj( "dévot" )
fradj( "ectopique" )
fradj( "effaré" )
fradj( "effectif" )
fradj( "effervescent" )
fradj( "effervescente" )
fradj( "efficace" )
fradj( "efficiente" )
fradj( "efflorescent" )
fradj( "efflorescente" )
fradj( "effrayante" )
fradj( "effrayé" )
fradj( "effroyable" )
fradj( "effréné" )
fradj( "effrénée" )
fradj( "efféminé" )
fradj( "elliptique" )
fradj( "embarrassante" )
fradj( "emblématique" )
fradj( "embroussaillé" )
fradj( "embryonnaire" )
fradj( "empesé" )
fradj( "emphatique" )
fradj( "empirique" )
fradj( "employable" )
fradj( "empoisonnant" )
fradj( "empêtré" )
fradj( "encaissable" )
fradj( "encalminé" )
fradj( "enclin" )
fradj( "encroûté" )
fradj( "encyclopédique" )
fradj( "endurable" )
fradj( "endémique" )
fradj( "enfantin" )
fradj( "enfichable" )
fradj( "enfoncé" )
fradj( "ennuyeux" )
fradj( "enquiquineur" )
fradj( "enrichissante" )
fradj( "ensommeillé" )
fradj( "enthousiasmant" )
fradj( "entière" )
fradj( "entraînable" )
fradj( "entérique" )
fradj( "entêté" )
fradj( "envisageable" )
fradj( "enzymatique" )
fradj( "ergonomique" )
fradj( "erratique" )
fradj( "erroné" )
fradj( "escamotable" )
fradj( "esclave" )
fradj( "escomptable" )
fradj( "escorteur" )
fradj( "espion" )
fradj( "espiègle" )
fradj( "essentiel" )
fradj( "essentielle" )
fradj( "esthète" )
fradj( "estimatif" )
fradj( "estudiantin" )
fradj( "ethnographique" )
fradj( "ethnologique" )
fradj( "euphonique" )
fradj( "euphorique" )
fradj( "eurasien" )
fradj( "eurythmique" )
fradj( "euscarien" )
fradj( "euskarien" )
fradj( "exacts" )
fradj( "exanthématique" )
fradj( "excellents" )
fradj( "exceptionnelle" )
fradj( "excessif" )
fradj( "excrémentiel" )
fradj( "excréteur" )
fradj( "excusable" )
fradj( "excédentaire" )
fradj( "exhaustif" )
fradj( "exigible" )
fradj( "existentiel" )
fradj( "existentielle" )
fradj( "exogène" )
fradj( "exorbitante" )
fradj( "exoréique" )
fradj( "exotique" )
fradj( "expansible" )
fradj( "expansif" )
fradj( "expiable" )
fradj( "expiatoire" )
fradj( "explicatif" )
fradj( "exploitable" )
fradj( "exploratoire" )
fradj( "exportateur" )
fradj( "expresse" )
fradj( "expressif" )
fradj( "exprimable" )
fradj( "expulsé" )
fradj( "expéditif" )
fradj( "expérimental" )
fradj( "exquise" )
fradj( "exsangue" )
fradj( "extenseur" )
fradj( "extensible" )
fradj( "extensif" )
fradj( "exterminateur" )
fradj( "extirpable" )
fradj( "extra-fin" )
fradj( "extractible" )
fradj( "extraordinaire" )
fradj( "extrinsèque" )
fradj( "extrorse" )
fradj( "extérieur" )
fradj( "extérieure" )
fradj( "exubérante" )
fradj( "exécutable" )
fradj( "exécutif" )
fradj( "fabulateur" )
fradj( "fabuleux" )
fradj( "faciles" )
fradj( "factitif" )
fradj( "factuel" )
fradj( "facultatif" )
fradj( "faiblard" )
fradj( "faisable" )
fradj( "fallacieux" )
fradj( "fameux" )
fradj( "famélique" )
fradj( "fangeux" )
fradj( "fantasmagorique" )
fradj( "fantasmatique" )
fradj( "fantasque" )
fradj( "fantastiques" )
fradj( "fantoche" )
fradj( "fantomatique" )
fradj( "fantôme" )
fradj( "faramineux" )
fradj( "farinacé" )
fradj( "fastidieux" )
fradj( "fastueux" )
fradj( "fatidique" )
fradj( "fatigant" )
fradj( "favorable" )
fradj( "favori" )
fradj( "façonnier" )
fradj( "fermante" )
fradj( "fermentable" )
fradj( "fermentescible" )
fradj( "fertilisable" )
fradj( "fessu" )
fradj( "festif" )
fradj( "feue" )
fradj( "feuillue" )
fradj( "fiable" )
fradj( "fibreux" )
fradj( "fictif" )
fradj( "fielleux" )
fradj( "figuratif" )
fradj( "filandreux" )
fradj( "filiforme" )
fradj( "filmique" )
fradj( "filtrable" )
fradj( "finassier" )
fradj( "finaud" )
fradj( "fissible" )
fradj( "fistuleux" )
fradj( "fière" )
fradj( "flagada" )
fradj( "flagrante" )
fradj( "flamboyante" )
fradj( "flatteur" )
fradj( "flemmard" )
fradj( "flexionnel" )
fradj( "flottable" )
fradj( "flottante" )
fradj( "fluet" )
fradj( "folichon" )
fradj( "folklorique" )
fradj( "follet" )
fradj( "folliculaire" )
fradj( "folâtrant" )
fradj( "foncier" )
fradj( "foncière" )
fradj( "fonctionnel" )
fradj( "fondamental" )
fradj( "fongible" )
fradj( "fongique" )
fradj( "fongueux" )
fradj( "forcené" )
fradj( "formateur" )
fradj( "formatif" )
fradj( "formaté" )
fradj( "formel" )
fradj( "formelle" )
fradj( "formulable" )
fradj( "fortrait" )
fradj( "fortuit" )
fradj( "fortuite" )
fradj( "fougueux" )
fradj( "fourbu" )
fradj( "fourchu" )
fradj( "fractionnaire" )
fradj( "fragmentaire" )
fradj( "franc-maçonnique" )
fradj( "franche" )
fradj( "franchissable" )
fradj( "franciscain" )
fradj( "franquiste" )
fradj( "fraternel" )
fradj( "fraternelle" )
fradj( "frauduleux" )
fradj( "friand" )
fradj( "fricoteur" )
fradj( "frigorifique" )
fradj( "frileux" )
fradj( "fringant" )
fradj( "fringante" )
fradj( "frison" )
fradj( "frissonnant" )
fradj( "frivole" )
fradj( "froide" )
fradj( "froissable" )
fradj( "fromental" )
fradj( "frontalier" )
fradj( "fructueux" )
fradj( "fruste" )
fradj( "frénétique" )
fradj( "fréquentable" )
fradj( "frêle" )
fradj( "fugace" )
fradj( "fulgurante" )
fradj( "fuligineux" )
fradj( "fumable" )
fradj( "fumant" )
fradj( "fumeux" )
fradj( "funiculaire" )
fradj( "funèbre" )
fradj( "funéraire" )
fradj( "fureteur" )
fradj( "furibard" )
fradj( "furibond" )
fradj( "furtif" )
fradj( "fusiforme" )
fradj( "futur" )
fradj( "fécal" )
fradj( "fécond" )
fradj( "fécondable" )
fradj( "fécondateur" )
fradj( "fédérateur" )
fradj( "fédératif" )
fradj( "féerique" )
fradj( "félon" )
fradj( "féminin" )
fradj( "fémoral" )
fradj( "férié" )
fradj( "féroce" )
fradj( "féru" )
fradj( "fétichiste" )
fradj( "fétide" )
fradj( "gagnable" )
fradj( "gaie" )
fradj( "gaillard" )
fradj( "galactique" )
fradj( "galactogène" )
fradj( "ganache" )
fradj( "ganglionnaire" )
fradj( "gangreneux" )
fradj( "ganoïde" )
fradj( "garante" )
fradj( "gargantuesque" )
fradj( "garçonnier" )
fradj( "gastrique" )
fradj( "gastronomique" )
fradj( "gaullien" )
fradj( "gazeux" )
fradj( "gazouilleur" )
fradj( "gemmifère" )
fradj( "gentille" )
fradj( "gentillet" )
fradj( "gentillette" )
fradj( "germain" )
fradj( "germanophone" )
fradj( "gestuel" )
fradj( "gibbeux" )
fradj( "giratoire" )
fradj( "girondin" )
fradj( "givreux" )
fradj( "glabre" )
fradj( "glaceux" )
fradj( "glacial" )
fradj( "glaireux" )
fradj( "glaiseux" )
fradj( "glandulaire" )
fradj( "glanduleux" )
fradj( "glauque" )
fradj( "global" )
fradj( "globuleux" )
fradj( "glorieux" )
fradj( "gluant" )
fradj( "gluante" )
fradj( "glutineux" )
fradj( "gnomique" )
fradj( "goguenard" )
fradj( "gommeux" )
fradj( "gonflable" )
fradj( "gouailleur" )
fradj( "gouailleux" )
fradj( "goudronneux" )
fradj( "goutteux" )
fradj( "gouvernable" )
fradj( "gouvernemental" )
fradj( "goûteux" )
fradj( "gracieux" )
fradj( "graduelle" )
fradj( "graisseux" )
fradj( "grammatical" )
fradj( "grand-ducal" )
fradj( "grandelet" )
fradj( "grandelette" )
fradj( "grandet" )
fradj( "grandette" )
fradj( "grandioses" )
fradj( "grandissante" )
fradj( "graniteux" )
fradj( "granitique" )
fradj( "granulaire" )
fradj( "granuleux" )
fradj( "granulée" )
fradj( "grasse" )
fradj( "grassouillet" )
fradj( "grassouillette" )
fradj( "gratuit" )
fradj( "gratuite" )
fradj( "graveleux" )
fradj( "gravide" )
fradj( "grelottant" )
fradj( "grimacier" )
fradj( "grimacière" )
fradj( "gringe" )
fradj( "grisâtre" )
fradj( "grivois" )
fradj( "grondeur" )
fradj( "grossier" )
fradj( "grossissante" )
fradj( "grossière" )
fradj( "grouillante" )
fradj( "grumeleux" )
fradj( "grégaire" )
fradj( "gueulard" )
fradj( "guilleret" )
fradj( "guttural" )
fradj( "guéable" )
fradj( "guérissable" )
fradj( "guérisseur" )
fradj( "géant" )
fradj( "gémissante" )
fradj( "génial" )
fradj( "génital" )
fradj( "génito-urinaire" )
fradj( "généalogique" )
fradj( "généralisable" )
fradj( "générateur" )
fradj( "génésique" )
fradj( "géodésique" )
fradj( "géométrique" )
fradj( "gênant" )
fradj( "habile" )
fradj( "habituelle" )
fradj( "habité" )
fradj( "haché" )
fradj( "hadal" )
fradj( "hagard" )
fradj( "haillonneux" )
fradj( "halitueux" )
fradj( "hallucinatoire" )
fradj( "harcelant" )
fradj( "harcelé" )
fradj( "hardie" )
fradj( "hargneux" )
fradj( "harmonieux" )
fradj( "hasardeux" )
fradj( "hautain" )
fradj( "hauturier" )
fradj( "hauturière" )
fradj( "haïssable" )
fradj( "hebdomadaire" )
fradj( "hectique" )
fradj( "heimatlos" )
fradj( "hellénique" )
fradj( "helvète" )
fradj( "helvétique" )
fradj( "herbeux" )
fradj( "herculéen" )
fradj( "herculéenne" )
fradj( "hermétique" )
fradj( "hexagonal" )
fradj( "hexapode" )
fradj( "hibernal" )
fradj( "hideux" )
fradj( "hilaire" )
fradj( "hilarant" )
fradj( "hilare" )
fradj( "hindoustani" )
fradj( "hippique" )
fradj( "hippophagique" )
fradj( "hippopotamesque" )
fradj( "hispanique" )
fradj( "histologique" )
fradj( "hivernal" )
fradj( "hiémal" )
fradj( "hiérarchique" )
fradj( "hiéroglyphique" )
fradj( "hommasse" )
fradj( "homogène" )
fradj( "homéopathique" )
fradj( "homérique" )
fradj( "honnête" )
fradj( "honorable" )
fradj( "honoraire" )
fradj( "honorifique" )
fradj( "honteux" )
fradj( "horizontal" )
fradj( "hormonal" )
fradj( "horodateur" )
fradj( "horripilant" )
fradj( "hospitalier" )
fradj( "hostiles" )
fradj( "houiller" )
fradj( "houleux" )
fradj( "huileux" )
fradj( "humain" )
fradj( "humaine" )
fradj( "humanitaire" )
fradj( "humanitariste" )
fradj( "humanoïde" )
fradj( "humble" )
fradj( "humoristique" )
fradj( "huppé" )
fradj( "hurlant" )
fradj( "huîtrier" )
fradj( "hydrodynamique" )
fradj( "hydrologique" )
fradj( "hydrominéral" )
fradj( "hydromécanique" )
fradj( "hydropneumatique" )
fradj( "hygiénique" )
fradj( "hygrométrique" )
fradj( "hygroscopique" )
fradj( "hyperbolique" )
fradj( "hyperboréen" )
fradj( "hyperboréenne" )
fradj( "hypersensible" )
fradj( "hypersonique" )
fradj( "hypnotique" )
fradj( "hypocalorique" )
fradj( "hypodermique" )
fradj( "hypogé" )
fradj( "hypophysaire" )
fradj( "hyposulfureux" )
fradj( "hypothétique" )
fradj( "hâbleur" )
fradj( "hâtif" )
fradj( "hébraïque" )
fradj( "hébreux" )
fradj( "hédoniste" )
fradj( "hégémonique" )
fradj( "hélicoïdal" )
fradj( "héroïque" )
fradj( "héréditaire" )
fradj( "hérétique" )
fradj( "hétéroclites" )
fradj( "hétérogène" )
fradj( "hétéromorphe" )
fradj( "ibérique" )
fradj( "ichtyoïde" )
fradj( "iconique" )
fradj( "iconoclaste" )
fradj( "identifiable" )
fradj( "identiques" )
fradj( "idiopathique" )
fradj( "idoine" )
fradj( "idyllique" )
fradj( "idéal" )
fradj( "idéale" )
fradj( "idéel" )
fradj( "idéographique" )
fradj( "idéologique" )
fradj( "ignominieux" )
fradj( "igné" )
fradj( "iliaque" )
fradj( "illicite" )
fradj( "illisible" )
fradj( "illogique" )
fradj( "illuminé" )
fradj( "illusoire" )
fradj( "illégal" )
fradj( "illégitime" )
fradj( "imaginatif" )
fradj( "imbattable" )
fradj( "imberbe" )
fradj( "imitable" )
fradj( "imitateur" )
fradj( "imitatif" )
fradj( "immaculé" )
fradj( "immangeable" )
fradj( "immanquable" )
fradj( "immarcescible" )
fradj( "immatérialiste" )
fradj( "immatériel" )
fradj( "immatérielle" )
fradj( "immensurable" )
fradj( "immettable" )
fradj( "imminente" )
fradj( "immodéré" )
fradj( "immonde" )
fradj( "immoral" )
fradj( "immotivé" )
fradj( "immuable" )
fradj( "immunitaire" )
fradj( "immunogène" )
fradj( "immunosuppresseur" )
fradj( "immémorial" )
fradj( "immérité" )
fradj( "impair" )
fradj( "imparable" )
fradj( "impardonnable" )
fradj( "imparfait" )
fradj( "imparfaite" )
fradj( "imparidigité" )
fradj( "impartageable" )
fradj( "impartiale" )
fradj( "impavide" )
fradj( "impayable" )
fradj( "impayée" )
fradj( "impensable" )
fradj( "imperceptibles" )
fradj( "imperdable" )
fradj( "imperfectible" )
fradj( "impersonnelle" )
fradj( "impitoyable" )
fradj( "implexe" )
fradj( "implicite" )
fradj( "impolitique" )
fradj( "impopulaire" )
fradj( "importable" )
fradj( "importants" )
fradj( "importateur" )
fradj( "importun" )
fradj( "imposants" )
fradj( "impotente" )
fradj( "impraticable" )
fradj( "imprenable" )
fradj( "impressionnable" )
fradj( "improductif" )
fradj( "impropre" )
fradj( "improuvable" )
fradj( "imprévisible" )
fradj( "imprévu" )
fradj( "impudique" )
fradj( "impur" )
fradj( "imputable" )
fradj( "imputrescible" )
fradj( "impécunieux" )
fradj( "impératif" )
fradj( "impérieux" )
fradj( "impérissable" )
fradj( "impétueux" )
fradj( "inabordable" )
fradj( "inaccentué" )
fradj( "inacceptable" )
fradj( "inaccordable" )
fradj( "inaccoutumé" )
fradj( "inachevé" )
fradj( "inachevée" )
fradj( "inactif" )
fradj( "inactuel" )
fradj( "inactuelle" )
fradj( "inadapté" )
fradj( "inadéquat" )
fradj( "inaltéré" )
fradj( "inamical" )
fradj( "inamissible" )
fradj( "inamovible" )
fradj( "inanimé" )
fradj( "inanimée" )
fradj( "inapaisable" )
fradj( "inapaisé" )
fradj( "inaperçu" )
fradj( "inapte" )
fradj( "inarticulé" )
fradj( "inassimilable" )
fradj( "inassouvi" )
fradj( "inassouvissable" )
fradj( "inattaquable" )
fradj( "inattendu" )
fradj( "inattentif" )
fradj( "inaugural" )
fradj( "inauthentique" )
fradj( "inavouable" )
fradj( "inavoué" )
fradj( "incapable" )
fradj( "incarnadin" )
fradj( "incarnat" )
fradj( "incassable" )
fradj( "incertain" )
fradj( "incertaine" )
fradj( "incessible" )
fradj( "inchangé" )
fradj( "inchavirable" )
fradj( "incisif" )
fradj( "incitatif" )
fradj( "incivil" )
fradj( "inclinable" )
fradj( "inclusif" )
fradj( "incoercible" )
fradj( "incolore" )
fradj( "incombustible" )
fradj( "incommensurable" )
fradj( "incommunicable" )
fradj( "incompatible" )
fradj( "incomplet" )
fradj( "incomplète" )
fradj( "incompressible" )
fradj( "incompris" )
fradj( "incompréhensif" )
fradj( "incompétent" )
fradj( "inconcevable" )
fradj( "inconciliable" )
fradj( "inconditionnel" )
fradj( "inconditionnelle" )
fradj( "inconfortable" )
fradj( "incongru" )
fradj( "incongrue" )
fradj( "inconnaissable" )
fradj( "inconsciente" )
fradj( "inconscients" )
fradj( "inconsidéré" )
fradj( "inconsistant" )
fradj( "inconsolé" )
fradj( "inconsommable" )
fradj( "inconstitutionnel" )
fradj( "inconstitutionnelle" )
fradj( "incontesté" )
fradj( "incontournable" )
fradj( "incontrôlable" )
fradj( "incontrôlé" )
fradj( "inconvenant" )
fradj( "inconvenante" )
fradj( "incorporable" )
fradj( "incorporel" )
fradj( "incorporelle" )
fradj( "increvable" )
fradj( "incriminable" )
fradj( "incrédule" )
fradj( "inculpable" )
fradj( "inculte" )
fradj( "incultivable" )
fradj( "incurieux" )
fradj( "indemne" )
fradj( "indemnisable" )
fradj( "indescriptible" )
fradj( "indianiste" )
fradj( "indiciaire" )
fradj( "indicible" )
fradj( "indiciel" )
fradj( "indicielle" )
fradj( "indien" )
fradj( "indifférencié" )
fradj( "indifférente" )
fradj( "indigeste" )
fradj( "indigène" )
fradj( "indigète" )
fradj( "indiqué" )
fradj( "indirecte" )
fradj( "indiscernable" )
fradj( "indiscret" )
fradj( "indiscutable" )
fradj( "indiscuté" )
fradj( "indispensables" )
fradj( "indisponible" )
fradj( "indissociable" )
fradj( "indivis" )
fradj( "indo-européen" )
fradj( "indolente" )
fradj( "indolore" )
fradj( "indomptable" )
fradj( "indompté" )
fradj( "indu" )
fradj( "inductif" )
fradj( "industrieux" )
fradj( "indéboulonnable" )
fradj( "indébrouillable" )
fradj( "indécent" )
fradj( "indécente" )
fradj( "indéchiffrable" )
fradj( "indécis" )
fradj( "indécomposable" )
fradj( "indécrottable" )
fradj( "indéfendable" )
fradj( "indéfini" )
fradj( "indéfinissable" )
fradj( "indéformable" )
fradj( "indélicat" )
fradj( "indélébile" )
fradj( "indémontrable" )
fradj( "indéniable" )
fradj( "indépassable" )
fradj( "indépendant" )
fradj( "indépendantiste" )
fradj( "indéracinable" )
fradj( "indésirable" )
fradj( "indéterminé" )
fradj( "ineffaçable" )
fradj( "inefficace" )
fradj( "inemployable" )
fradj( "inemployé" )
fradj( "inentamé" )
fradj( "inenvisageable" )
fradj( "inepte" )
fradj( "inerte" )
fradj( "inespéré" )
fradj( "inesthétique" )
fradj( "inexacte" )
fradj( "inexistant" )
fradj( "inexistante" )
fradj( "inexpliqué" )
fradj( "inexploitable" )
fradj( "inexploité" )
fradj( "inexploré" )
fradj( "inexpressif" )
fradj( "inexprimable" )
fradj( "inexprimé" )
fradj( "inexpugnable" )
fradj( "inexpérimenté" )
fradj( "inextinguible" )
fradj( "inextirpable" )
fradj( "inexécutable" )
fradj( "infaillible" )
fradj( "infaisable" )
fradj( "infamant" )
fradj( "infatigable" )
fradj( "infect" )
fradj( "infectieux" )
fradj( "infermentescible" )
fradj( "infernale" )
fradj( "infernal" )
fradj( "infime" )
fradj( "infinie" )
fradj( "infinitésimal" )
fradj( "infirmatif" )
fradj( "influençable" )
fradj( "informatif" )
fradj( "informel" )
fradj( "informelle" )
fradj( "informulé" )
fradj( "infortuné" )
fradj( "infortunée" )
fradj( "infranchissable" )
fradj( "infroissable" )
fradj( "infructueux" )
fradj( "infus" )
fradj( "infâme" )
fradj( "infécond" )
fradj( "inférovarié" )
fradj( "ingambe" )
fradj( "ingouvernable" )
fradj( "ingrat" )
fradj( "inguérissable" )
fradj( "ingénieux" )
fradj( "inhabile" )
fradj( "inhabitable" )
fradj( "inhabituel" )
fradj( "inhabituelle" )
fradj( "inhabité" )
fradj( "inhibitif" )
fradj( "inhospitalier" )
fradj( "inhospitalière" )
fradj( "inhumain" )
fradj( "inhumaine" )
fradj( "inimaginable" )
fradj( "ininflammable" )
fradj( "inintelligent" )
fradj( "inintelligible" )
fradj( "ininterrompu" )
fradj( "inintéressant" )
fradj( "inique" )
fradj( "initial" )
fradj( "initiatique" )
fradj( "injonctif" )
fradj( "injouable" )
fradj( "injurieux" )
fradj( "injuste" )
fradj( "injustifiable" )
fradj( "injustifié" )
fradj( "inlassable" )
fradj( "innombrable" )
fradj( "innommable" )
fradj( "inné" )
fradj( "inoccupé" )
fradj( "inoccupée" )
fradj( "inoculable" )
fradj( "inodore" )
fradj( "inoffensif" )
fradj( "inondable" )
fradj( "inopiné" )
fradj( "inopportun" )
fradj( "inopposable" )
fradj( "inopérant" )
fradj( "inorganique" )
fradj( "inorganisé" )
fradj( "inorganisée" )
fradj( "inoubliable" )
fradj( "inouï" )
fradj( "inoxydable" )
fradj( "inqualifiable" )
fradj( "inquiet" )
fradj( "inquisitorial" )
fradj( "inquiétante" )
fradj( "inracontable" )
fradj( "insaisissable" )
fradj( "insalubre" )
fradj( "insatisfaisant" )
fradj( "insatisfait" )
fradj( "insatisfaite" )
fradj( "insensible" )
fradj( "insensée" )
fradj( "insermenté" )
fradj( "insidieux" )
fradj( "insignifiant" )
fradj( "insipide" )
fradj( "insistant" )
fradj( "insociable" )
fradj( "insolite" )
fradj( "insondable" )
fradj( "insoucieux" )
fradj( "insoumis" )
fradj( "insoumise" )
fradj( "insoupçonnable" )
fradj( "insoupçonné" )
fradj( "insoutenable" )
fradj( "instable" )
fradj( "instantané" )
fradj( "instante" )
fradj( "instinctuel" )
fradj( "institutionnel" )
fradj( "institutionnelle" )
fradj( "instructif" )
fradj( "insubmersible" )
fradj( "insubordonné" )
fradj( "insuffisant" )
fradj( "insuffisante" )
fradj( "insultante" )
fradj( "insurgé" )
fradj( "insurmontable" )
fradj( "insurpassable" )
fradj( "insécable" )
fradj( "insérable" )
fradj( "intacte" )
fradj( "intactile" )
fradj( "intarissable" )
fradj( "intelligente" )
fradj( "intempestif" )
fradj( "intemporel" )
fradj( "intemporelle" )
fradj( "intempérant" )
fradj( "intenable" )
fradj( "intentionnel" )
fradj( "intentionnelle" )
fradj( "interactif" )
fradj( "interchangeable" )
fradj( "intercotidal" )
fradj( "interdisciplinaire" )
fradj( "interdépendant" )
fradj( "interlope" )
fradj( "interpersonnel" )
fradj( "interpersonnelle" )
fradj( "interplanétaire" )
fradj( "interrogatif" )
fradj( "intersidéral" )
fradj( "interstellaire" )
fradj( "intestinal" )
fradj( "intimidateur" )
fradj( "intolérant" )
fradj( "intracrânien" )
fradj( "intraduisible" )
fradj( "intraitable" )
fradj( "intransmissible" )
fradj( "intrinsèque" )
fradj( "introductif" )
fradj( "introuvable" )
fradj( "intrus" )
fradj( "intruse" )
fradj( "intrépide" )
fradj( "intégrable" )
fradj( "intégrante" )
fradj( "intégral" )
fradj( "intégriste" )
fradj( "intérieure" )
fradj( "intéroceptif" )
fradj( "inusable" )
fradj( "inusité" )
fradj( "inusuel" )
fradj( "inutile" )
fradj( "inutilisable" )
fradj( "inutilisé" )
fradj( "invendable" )
fradj( "invendue" )
fradj( "inventif" )
fradj( "invivable" )
fradj( "involontaire" )
fradj( "invraisemblable" )
fradj( "invérifiable" )
fradj( "inébranlable" )
fradj( "inécoutable" )
fradj( "inécouté" )
fradj( "inédite" )
fradj( "inégal" )
fradj( "inégalable" )
fradj( "inélégante" )
fradj( "inénarrable" )
fradj( "inéprouvé" )
fradj( "inépuisable" )
fradj( "inépuisé" )
fradj( "iranien" )
fradj( "ironique" )
fradj( "irraisonné" )
fradj( "irrattrapable" )
fradj( "irrecevable" )
fradj( "irremplaçable" )
fradj( "irrespectueux" )
fradj( "irrespirable" )
fradj( "irrigable" )
fradj( "irritante" )
fradj( "irréalisable" )
fradj( "irréaliste" )
fradj( "irréconciliable" )
fradj( "irrécupérable" )
fradj( "irréductible" )
fradj( "irréelle" )
fradj( "irréfléchi" )
fradj( "irréfléchie" )
fradj( "irréformable" )
fradj( "irrégulier" )
fradj( "irréligieux" )
fradj( "irréprochable" )
fradj( "irrépréhensible" )
fradj( "irrésolu" )
fradj( "irrévérencieux" )
fradj( "irénique" )
fradj( "islamique" )
fradj( "isochrone" )
fradj( "isolable" )
fradj( "israélien" )
fradj( "issu" )
fradj( "itinéraire" )
fradj( "itératif" )
fradj( "ivoirin" )
fradj( "ivre" )
fradj( "jaculatoire" )
fradj( "jaillissante" )
fradj( "jaunâtre" )
fradj( "jetable" )
fradj( "jeunot" )
fradj( "jeunotte" )
fradj( "jolie" )
fradj( "jouable" )
fradj( "joufflu" )
fradj( "jouisseur" )
fradj( "jouissif" )
fradj( "journalier" )
fradj( "journalistique" )
fradj( "judaïque" )
fradj( "judiciaire" )
fradj( "judicieux" )
fradj( "jugal" )
fradj( "jugeable" )
fradj( "juif" )
fradj( "julien" )
fradj( "jupitérien" )
fradj( "juridique" )
fradj( "justificateur" )
fradj( "justificatif" )
fradj( "kafkaïen" )
fradj( "kaléidoscopique" )
fradj( "kanak" )
fradj( "kymrique" )
fradj( "labourable" )
fradj( "laconique" )
fradj( "lactescente" )
fradj( "lacté" )
fradj( "lactée" )
fradj( "lacunaire" )
fradj( "lacuneux" )
fradj( "lacustre" )
fradj( "laid" )
fradj( "laide" )
fradj( "laineux" )
fradj( "laiteux" )
fradj( "laitier" )
fradj( "langoureux" )
fradj( "languide" )
fradj( "languissante" )
fradj( "largable" )
fradj( "larges" )
fradj( "larmoyante" )
fradj( "larvaire" )
fradj( "larvé" )
fradj( "lascif" )
fradj( "lassante" )
fradj( "latitudinaire" )
fradj( "latéral" )
fradj( "laudatif" )
fradj( "lavable" )
fradj( "laxatif" )
fradj( "laïusseur" )
fradj( "lent" )
fradj( "lenticulaire" )
fradj( "lentiforme" )
fradj( "lessivable" )
fradj( "letton" )
fradj( "levé" )
fradj( "lexical" )
fradj( "lexicographique" )
fradj( "libidinal" )
fradj( "libre" )
fradj( "libyen" )
fradj( "licencieux" )
fradj( "lige" )
fradj( "lilial" )
fradj( "lilliputien" )
fradj( "liminaire" )
fradj( "liminal" )
fradj( "limitatif" )
fradj( "limitrophe" )
fradj( "limoneux" )
fradj( "limpide" )
fradj( "linéal" )
fradj( "liquidable" )
fradj( "liquoreux" )
fradj( "lisible" )
fradj( "lithographe" )
fradj( "lithuanien" )
fradj( "litigieux" )
fradj( "liturgique" )
fradj( "livide" )
fradj( "livresque" )
fradj( "localisable" )
fradj( "logeable" )
fradj( "lointaine" )
fradj( "loisible" )
fradj( "longitudinal" )
fradj( "loquace" )
fradj( "loqueteux" )
fradj( "louable" )
fradj( "lourdingue" )
fradj( "loyal" )
fradj( "lubrique" )
fradj( "lucide" )
fradj( "lucratif" )
fradj( "ludique" )
fradj( "lugubre" )
fradj( "luisante" )
fradj( "luminescent" )
fradj( "lumineux" )
fradj( "lusitanien" )
fradj( "lutin" )
fradj( "luxembourgeois" )
fradj( "luxueux" )
fradj( "luxurieux" )
fradj( "lymphatique" )
fradj( "lymphoïde" )
fradj( "lège" )
fradj( "légal" )
fradj( "légendaire" )
fradj( "léger" )
fradj( "légère" )
fradj( "lénifiante" )
fradj( "lénitif" )
fradj( "léonin" )
fradj( "lésionnel" )
fradj( "létal" )
fradj( "léthargique" )
fradj( "machiavélique" )
fradj( "machinal" )
fradj( "machiste" )
fradj( "macrocosmique" )
fradj( "madré" )
fradj( "mafflu" )
fradj( "maghrébin" )
fradj( "magique" )
fradj( "magistral" )
fradj( "magmatique" )
fradj( "magnanime" )
fradj( "magnifique" )
fradj( "magnétique" )
fradj( "magyare" )
fradj( "maigrelet" )
fradj( "maigrichon" )
fradj( "maigriot" )
fradj( "majestueux" )
fradj( "majeur" )
fradj( "malade" )
fradj( "maladif" )
fradj( "maladroite" )
fradj( "malaire" )
fradj( "malavisé" )
fradj( "malcommode" )
fradj( "malencontreux" )
fradj( "malentendant" )
fradj( "malfaisant" )
fradj( "malfamé" )
fradj( "malhabile" )
fradj( "malheureux" )
fradj( "malhonnêtes" )
fradj( "malicieux" )
fradj( "maligne" )
fradj( "malin" )
fradj( "malingre" )
fradj( "malodorant" )
fradj( "malotru" )
fradj( "malpoli" )
fradj( "malsain" )
fradj( "malsonnant" )
fradj( "malséant" )
fradj( "malveillant" )
fradj( "malvenu" )
fradj( "maléfique" )
fradj( "manchot" )
fradj( "mandarin" )
fradj( "mangeable" )
fradj( "maniable" )
fradj( "manoeuvrable" )
fradj( "manuscrit" )
fradj( "maous" )
fradj( "maraudeur" )
fradj( "mariable" )
fradj( "marinier" )
fradj( "marmoréen" )
fradj( "marneux" )
fradj( "marqueté" )
fradj( "marqueur" )
fradj( "martiale" )
fradj( "martien" )
fradj( "marécageux" )
fradj( "matinal" )
fradj( "matineux" )
fradj( "matriarcal" )
fradj( "matricielle" )
fradj( "matrimonial" )
fradj( "matutinal" )
fradj( "maussade" )
fradj( "maçonnique" )
fradj( "maîtrisable" )
fradj( "membru" )
fradj( "mensonger" )
fradj( "menstruel" )
fradj( "mental" )
fradj( "menteur" )
fradj( "menue" )
fradj( "merveilleux" )
fradj( "mesquin" )
fradj( "mesquine" )
fradj( "mesurable" )
fradj( "mettable" )
fradj( "meunier" )
fradj( "mi-clos" )
fradj( "mi-fin" )
fradj( "miasmatique" )
fradj( "microbien" )
fradj( "microscopique" )
fradj( "mielleux" )
fradj( "mignonnet" )
fradj( "migrateur" )
fradj( "milliardaire" )
fradj( "minable" )
fradj( "mineur" )
fradj( "ministériel" )
fradj( "minoratif" )
fradj( "miraculeux" )
fradj( "mirobolant" )
fradj( "misogyne" )
fradj( "missionnaire" )
fradj( "miséricordieux" )
fradj( "mitigé" )
fradj( "mitoyen" )
fradj( "mièvre" )
fradj( "mobilier" )
fradj( "mobilisateur" )
fradj( "modeleur" )
fradj( "modeste" )
fradj( "modifiable" )
fradj( "modique" )
fradj( "moelleux" )
fradj( "moindre" )
fradj( "moite" )
fradj( "momentané" )
fradj( "monacal" )
fradj( "monastique" )
fradj( "mondial" )
fradj( "mongol" )
fradj( "mongolien" )
fradj( "monnayable" )
fradj( "monocellulaire" )
fradj( "monoclinique" )
fradj( "monocorde" )
fradj( "monolingue" )
fradj( "monomane" )
fradj( "monomaniaque" )
fradj( "monophonique" )
fradj( "monoïque" )
fradj( "monstre" )
fradj( "monstrueux" )
fradj( "montagneux" )
fradj( "monteur" )
fradj( "monticole" )
fradj( "montrable" )
fradj( "montueux" )
fradj( "monumental" )
fradj( "monétaire" )
fradj( "moral" )
fradj( "moralisateur" )
fradj( "morbide" )
fradj( "morcelable" )
fradj( "morphinomane" )
fradj( "morphologique" )
fradj( "morutier" )
fradj( "moteur" )
fradj( "motivante" )
fradj( "mou" )
fradj( "mouillée" )
fradj( "moulé" )
fradj( "mousseux" )
fradj( "moutonneux" )
fradj( "moutonnier" )
fradj( "mouvementé" )
fradj( "moyenâgeux" )
fradj( "mulassière" )
fradj( "multicellulaire" )
fradj( "multicolore" )
fradj( "multidimensionnel" )
fradj( "multidisciplinaire" )
fradj( "multiforme" )
fradj( "multilatéral" )
fradj( "multinational" )
fradj( "mulâtre" )
fradj( "musculeux" )
fradj( "musicien" )
fradj( "mutuels" )
fradj( "mythique" )
fradj( "mythologique" )
fradj( "méconnaissable" )
fradj( "médiat" )
fradj( "médical" )
fradj( "médicinal" )
fradj( "méditatif" )
fradj( "médiéval" )
fradj( "médullaire" )
fradj( "mélancolique" )
fradj( "mélangeur" )
fradj( "mélanique" )
fradj( "mélodieux" )
fradj( "mélodramatique" )
fradj( "méphistophélique" )
fradj( "méphitique" )
fradj( "méprisable" )
fradj( "méprisante" )
fradj( "méritant" )
fradj( "méritoire" )
fradj( "métallurgique" )
fradj( "métaphorique" )
fradj( "méthodique" )
fradj( "météorologique" )
fradj( "môme" )
fradj( "mûr" )
fradj( "nain" )
fradj( "narcissique" )
fradj( "narquoise" )
fradj( "natif" )
fradj( "national" )
fradj( "naturaliste" )
fradj( "naturiste" )
fradj( "naufragé" )
fradj( "nauséabond" )
fradj( "nauséeux" )
fradj( "nautique" )
fradj( "navigateur" )
fradj( "navrante" )
fradj( "neigeux" )
fradj( "neurodépresseur" )
fradj( "neuve" )
fradj( "niable" )
fradj( "nitrique" )
fradj( "nième" )
fradj( "noceur" )
fradj( "nocif" )
fradj( "nodal" )
fradj( "noiraud" )
fradj( "noirâtre" )
fradj( "nombrable" )
fradj( "nombreux" )
fradj( "nominatif" )
fradj( "non-aligné" )
fradj( "non-engagé" )
fradj( "non-figuratif" )
fradj( "non-violent" )
fradj( "nord-africain" )
fradj( "nord-américain" )
fradj( "nord-américaine" )
fradj( "nordique" )
fradj( "normatif" )
fradj( "normal" )
fradj( "notarié" )
fradj( "notionnel" )
fradj( "notoire" )
fradj( "noueux" )
fradj( "nourricier" )
fradj( "nourricière" )
fradj( "nouvel" )
fradj( "novateur" )
fradj( "novatoire" )
fradj( "noétique" )
fradj( "nuageux" )
fradj( "numéraire" )
fradj( "numérique" )
fradj( "nutritif" )
fradj( "nutritionnel" )
fradj( "nymphomane" )
fradj( "nébuleux" )
fradj( "néfaste" )
fradj( "négligeable" )
fradj( "négociable" )
fradj( "néolithique" )
fradj( "néphrétique" )
fradj( "névralgique" )
fradj( "oblatif" )
fradj( "obligatoire" )
fradj( "obligeants" )
fradj( "oblongue" )
fradj( "obscur" )
fradj( "obscènes" )
fradj( "observable" )
fradj( "obsessionnel" )
fradj( "obsessionnelle" )
fradj( "obstructif" )
fradj( "obséquieux" )
fradj( "obtus" )
fradj( "obtusangle" )
fradj( "occasionnel" )
fradj( "occasionnelle" )
fradj( "occitan" )
fradj( "occlusif" )
fradj( "occurrent" )
fradj( "ocellé" )
fradj( "ocreux" )
fradj( "oculomoteur" )
fradj( "océanique" )
fradj( "océanographique" )
fradj( "odieux" )
fradj( "odoriférant" )
fradj( "oecuménique" )
fradj( "oestral" )
fradj( "oeuvé" )
fradj( "offensante" )
fradj( "offensif" )
fradj( "officieux" )
fradj( "oghamique" )
fradj( "ogival" )
fradj( "oiseux" )
fradj( "olivâtre" )
fradj( "olympien" )
fradj( "oléagineux" )
fradj( "oléifiant" )
fradj( "oléiforme" )
fradj( "oléifère" )
fradj( "ombrageux" )
fradj( "ombragé" )
fradj( "ombragée" )
fradj( "ombreux" )
fradj( "omnipotente" )
fradj( "onctueux" )
fradj( "ondoyante" )
fradj( "ondulant" )
fradj( "ondulante" )
fradj( "onduleux" )
fradj( "ondulé" )
fradj( "onguligrade" )
fradj( "ongulé" )
fradj( "ongulée" )
fradj( "onirique" )
fradj( "ontologique" )
fradj( "onéreux" )
fradj( "oolithique" )
fradj( "opalin" )
fradj( "ophidien" )
fradj( "ophtalmique" )
fradj( "opimes" )
fradj( "opportun" )
fradj( "opportuniste" )
fradj( "oppressante" )
fradj( "oppressif" )
fradj( "opprimant" )
fradj( "optatif" )
fradj( "optimal" )
fradj( "optionnel" )
fradj( "opulente" )
fradj( "opérante" )
fradj( "opérationnel" )
fradj( "opératoire" )
fradj( "orageux" )
fradj( "orant" )
fradj( "orbe" )
fradj( "orbiculaire" )
fradj( "ordinal" )
fradj( "ordurier" )
fradj( "ordurière" )
fradj( "organique" )
fradj( "organisateur" )
fradj( "orientable" )
fradj( "originaire" )
fradj( "original" )
fradj( "originel" )
fradj( "originelle" )
fradj( "ornemaniste" )
fradj( "ornemental" )
fradj( "orthogonal" )
fradj( "osseux" )
fradj( "ossu" )
fradj( "ostentatoire" )
fradj( "osée" )
fradj( "otique" )
fradj( "oubliable" )
fradj( "ouralien" )
fradj( "outrageux" )
fradj( "outragé" )
fradj( "outrancier" )
fradj( "outrancière" )
fradj( "outrée" )
fradj( "ouvrable" )
fradj( "ouvragé" )
fradj( "ovoïdal" )
fradj( "ovoïde" )
fradj( "pailleux" )
fradj( "paisible" )
fradj( "palliatif" )
fradj( "palmiste" )
fradj( "palustre" )
fradj( "paléographique" )
fradj( "paléontologique" )
fradj( "panard" )
fradj( "pansu" )
fradj( "pantagruélique" )
fradj( "pantois" )
fradj( "pantoise" )
fradj( "papal" )
fradj( "paperassier" )
fradj( "papillotant" )
fradj( "paradisiaque" )
fradj( "paralogique" )
fradj( "parasismique" )
fradj( "parastatal" )
fradj( "parastatale" )
fradj( "parcellaire" )
fradj( "parcimonieux" )
fradj( "pardonnable" )
fradj( "parental" )
fradj( "paritaire" )
fradj( "parlante" )
fradj( "parnassien" )
fradj( "parodique" )
fradj( "paroxysmique" )
fradj( "paroxystique" )
fradj( "partageable" )
fradj( "partageur" )
fradj( "partial" )
fradj( "particulière" )
fradj( "partisane" )
fradj( "partisans" )
fradj( "passionnel" )
fradj( "passionnelle" )
fradj( "pastoral" )
fradj( "pathologique" )
fradj( "patibulaire" )
fradj( "patriarcal" )
fradj( "patrilocal" )
fradj( "patriotique" )
fradj( "pattu" )
fradj( "paulien" )
fradj( "peinard" )
fradj( "pelletier" )
fradj( "pellucide" )
fradj( "penaud" )
fradj( "pendable" )
fradj( "pendante" )
fradj( "pensable" )
fradj( "pensif" )
fradj( "pentu" )
fradj( "perceptibles" )
fradj( "perceptif" )
fradj( "perceur" )
fradj( "percevable" )
fradj( "perfectible" )
fradj( "perfide" )
fradj( "perforé" )
fradj( "permissif" )
fradj( "permutable" )
fradj( "pernicieux" )
fradj( "perplexe" )
fradj( "perpétuel" )
fradj( "perpétuelle" )
fradj( "pers" )
fradj( "personnelle" )
fradj( "perspectif" )
fradj( "perspicace" )
fradj( "persuadé" )
fradj( "persuasif" )
fradj( "persécuteur" )
fradj( "pertinente" )
fradj( "pesante" )
fradj( "pesteux" )
fradj( "pestilentiel" )
fradj( "petiot" )
fradj( "phalanstérien" )
fradj( "pharamineux" )
fradj( "pharaonique" )
fradj( "philanthropique" )
fradj( "philharmonique" )
fradj( "philistin" )
fradj( "philosophique" )
fradj( "phonateur" )
fradj( "phonatoire" )
fradj( "phonique" )
fradj( "phonologique" )
fradj( "phonétique" )
fradj( "phosphorescent" )
fradj( "phosphorescente" )
fradj( "photogène" )
fradj( "physiologique" )
fradj( "phénoménale" )
fradj( "phénoménal" )
fradj( "piaculaire" )
fradj( "piailleur" )
fradj( "pictographique" )
fradj( "pierreux" )
fradj( "pieux" )
fradj( "pigmentaire" )
fradj( "pilaire" )
fradj( "pileux" )
fradj( "pimpant" )
fradj( "pinchard" )
fradj( "piquante" )
fradj( "pisciforme" )
fradj( "pisseux" )
fradj( "piteux" )
fradj( "pithiatique" )
fradj( "pitoyable" )
fradj( "pituitaire" )
fradj( "piètre" )
fradj( "piétonnier" )
fradj( "placide" )
fradj( "plaintif" )
fradj( "planimétrique" )
fradj( "plantureux" )
fradj( "platonique" )
fradj( "pleine" )
fradj( "pleureur" )
fradj( "pleurnicheur" )
fradj( "ployable" )
fradj( "plural" )
fradj( "pluricellulaire" )
fradj( "pluridimensionnel" )
fradj( "pluridisciplinaire" )
fradj( "plurielle" )
fradj( "plurilatéral" )
fradj( "plurinational" )
fradj( "plurivalent" )
fradj( "plurivoque" )
fradj( "plutonien" )
fradj( "plutonique" )
fradj( "pluvieux" )
fradj( "plâtrier" )
fradj( "plébéien" )
fradj( "plénier" )
fradj( "plénière" )
fradj( "pléonastique" )
fradj( "pléthorique" )
fradj( "poilant" )
fradj( "poilue" )
fradj( "pointillé" )
fradj( "pointue" )
fradj( "poissard" )
fradj( "poisseux" )
fradj( "poissonnier" )
fradj( "policière" )
fradj( "poltron" )
fradj( "polygame" )
fradj( "polyglotte" )
fradj( "polymorphe" )
fradj( "polypétale" )
fradj( "polysémique" )
fradj( "polytonal" )
fradj( "pompette" )
fradj( "pompeux" )
fradj( "pompier" )
fradj( "ponctuel" )
fradj( "pontifical" )
fradj( "populacier" )
fradj( "populaire" )
fradj( "populeux" )
fradj( "porcin" )
fradj( "poreux" )
fradj( "pornographique" )
fradj( "portatif" )
fradj( "positif" )
fradj( "possessif" )
fradj( "posthume" )
fradj( "postérieur" )
fradj( "potestatif" )
fradj( "poudreux" )
fradj( "poupin" )
fradj( "pourfendeur" )
fradj( "poussif" )
fradj( "poussiéreux" )
fradj( "praticien" )
fradj( "prenable" )
fradj( "presbytérien" )
fradj( "prescriptible" )
fradj( "pressante" )
fradj( "preste" )
fradj( "prestigieux" )
fradj( "primesautier" )
fradj( "primesautière" )
fradj( "primitif" )
fradj( "primordial" )
fradj( "princeps" )
fradj( "princier" )
fradj( "princière" )
fradj( "printanier" )
fradj( "prismatique" )
fradj( "prisonnier" )
fradj( "probant" )
fradj( "probatoire" )
fradj( "probes" )
fradj( "processif" )
fradj( "prochain" )
fradj( "procréateur" )
fradj( "prodigieux" )
fradj( "prodromique" )
fradj( "productif" )
fradj( "profanateur" )
fradj( "professoral" )
fradj( "profus" )
fradj( "programmable" )
fradj( "programmateur" )
fradj( "prohibitif" )
fradj( "prolifique" )
fradj( "prolixe" )
fradj( "prolétarien" )
fradj( "prometteur" )
fradj( "promotionnel" )
fradj( "promotionnelle" )
fradj( "prompt" )
fradj( "prompte" )
fradj( "prononçable" )
fradj( "prophylactique" )
fradj( "prophétique" )
fradj( "propice" )
fradj( "proportionnel" )
fradj( "propret" )
fradj( "prorogatif" )
fradj( "prosaïque" )
fradj( "prospectif" )
fradj( "protidique" )
fradj( "protocolaire" )
fradj( "protéiforme" )
fradj( "protéique" )
fradj( "prouvable" )
fradj( "provençal" )
fradj( "providentiel" )
fradj( "provisionnel" )
fradj( "provocant" )
fradj( "provocante" )
fradj( "proéminent" )
fradj( "prudhommesque" )
fradj( "prurigineux" )
fradj( "prussien" )
fradj( "prussique" )
fradj( "précaire" )
fradj( "précambrien" )
fradj( "précautionneux" )
fradj( "précoce" )
fradj( "préconçu" )
fradj( "prédateur" )
fradj( "prédicatif" )
fradj( "préférentiel" )
fradj( "préférentielle" )
fradj( "prégnant" )
fradj( "prégnante" )
fradj( "préhenseur" )
fradj( "préhistorique" )
fradj( "préjudiciable" )
fradj( "prélogique" )
fradj( "prémonitoire" )
fradj( "préparatoire" )
fradj( "prépositif" )
fradj( "prépositionnel" )
fradj( "préservateur" )
fradj( "présomptif" )
fradj( "présumable" )
fradj( "prétorial" )
fradj( "prévaricateur" )
fradj( "préventif" )
fradj( "prévisible" )
fradj( "prévisionnel" )
fradj( "prééminent" )
fradj( "prêt" )
fradj( "prêteur" )
fradj( "psychanalytique" )
fradj( "psychique" )
fradj( "psychologique" )
fradj( "psychosomatique" )
fradj( "pubescent" )
fradj( "publiable" )
fradj( "publicitaire" )
fradj( "publique" )
fradj( "pudibond" )
fradj( "pudique" )
fradj( "pugnace" )
fradj( "puissante" )
fradj( "puissants" )
fradj( "pulpeux" )
fradj( "pulsionnel" )
fradj( "punique" )
fradj( "punissable" )
fradj( "punitif" )
fradj( "pur" )
fradj( "purgatif" )
fradj( "puritain" )
fradj( "pustuleux" )
fradj( "putatif" )
fradj( "putrescible" )
fradj( "putride" )
fradj( "putréfiable" )
fradj( "putschiste" )
fradj( "puéril" )
fradj( "puîné" )
fradj( "pygmée" )
fradj( "pyramidal" )
fradj( "pâlichon" )
fradj( "pâlot" )
fradj( "pâteux" )
fradj( "pèlerin" )
fradj( "pécheur" )
fradj( "pécuniaire" )
fradj( "pédagogique" )
fradj( "pédantesque" )
fradj( "pédestre" )
fradj( "péjoratif" )
fradj( "pélagien" )
fradj( "pélagique" )
fradj( "pénible" )
fradj( "pénitentiaire" )
fradj( "pénétrable" )
fradj( "péremptoire" )
fradj( "pérennant" )
fradj( "pérenne" )
fradj( "périlleux" )
fradj( "périssable" )
fradj( "péroreur" )
fradj( "pétant" )
fradj( "pétillante" )
fradj( "pétrifiant" )
fradj( "pétrolier" )
fradj( "pétré" )
fradj( "pétulante" )
fradj( "pétéchial" )
fradj( "quadrangulaire" )
fradj( "qualifiable" )
fradj( "qualificatif" )
fradj( "quantifiable" )
fradj( "quantitatif" )
fradj( "quelconque" )
fradj( "querelleur" )
fradj( "quinaud" )
fradj( "quincaillier" )
fradj( "quinquagénaire" )
fradj( "quinteux" )
fradj( "quotidien" )
fradj( "rabelaisien" )
fradj( "raboteux" )
fradj( "raccommodable" )
fradj( "rachetable" )
fradj( "rachidien" )
fradj( "radieux" )
fradj( "rageur" )
fradj( "raide" )
fradj( "raisonnable" )
fradj( "rameux" )
fradj( "ramingue" )
fradj( "raplapla" )
fradj( "rares" )
fradj( "rarissime" )
fradj( "rationnelle" )
fradj( "rattrapable" )
fradj( "ravitailleur" )
fradj( "recevable" )
fradj( "recommandable" )
fradj( "reconductible" )
fradj( "reconnaissable" )
fradj( "recouvrable" )
fradj( "recru" )
fradj( "recrudescent" )
fradj( "rectangulaire" )
fradj( "recteur" )
fradj( "rectifiable" )
fradj( "rectificateur" )
fradj( "rectificatif" )
fradj( "recyclable" )
fradj( "redoutable" )
fradj( "refusable" )
fradj( "regardable" )
fradj( "regimbeur" )
fradj( "regrattier" )
fradj( "relevable" )
fradj( "religieux" )
fradj( "remarquable" )
fradj( "remboursable" )
fradj( "remplaçable" )
fradj( "remédiable" )
fradj( "renouvelable" )
fradj( "replet" )
fradj( "repliable" )
fradj( "repoussant" )
fradj( "repoussante" )
fradj( "reprochable" )
fradj( "reproducteur" )
fradj( "représentatif" )
fradj( "repérable" )
fradj( "respectif" )
fradj( "respectueux" )
fradj( "resplendissante" )
fradj( "restante" )
fradj( "restituable" )
fradj( "restrictif" )
fradj( "retardateur" )
fradj( "retrouvable" )
fradj( "revendicatif" )
fradj( "revêche" )
fradj( "rhumatisant" )
fradj( "rhétoricien" )
fradj( "ricaneur" )
fradj( "richissime" )
fradj( "rigide" )
fradj( "rigolard" )
fradj( "rigolo" )
fradj( "rigoureux" )
fradj( "rikiki" )
fradj( "riquiqui" )
fradj( "rituelle" )
fradj( "roboratif" )
fradj( "robuste" )
fradj( "rocailleux" )
fradj( "rocambolesque" )
fradj( "rocheux" )
fradj( "rogué" )
fradj( "roide" )
fradj( "roman" )
fradj( "rondelet" )
fradj( "rongeur" )
fradj( "rosâtre" )
fradj( "rotatif" )
fradj( "rotatoire" )
fradj( "rotulien" )
fradj( "roturier" )
fradj( "roublard" )
fradj( "rougeâtre" )
fradj( "rouspéteur" )
fradj( "roussâtre" )
fradj( "routinier" )
fradj( "royal" )
fradj( "rubescent" )
fradj( "rubicond" )
fradj( "rubigineux" )
fradj( "rudimentaire" )
fradj( "rugissante" )
fradj( "ruineux" )
fradj( "rupestre" )
fradj( "rustaud" )
fradj( "rutilante" )
fradj( "râlant" )
fradj( "râpeux" )
fradj( "réalisable" )
fradj( "rébarbatif" )
fradj( "récapitulatif" )
fradj( "récente" )
fradj( "récepteur" )
fradj( "réceptif" )
fradj( "réceptionniste" )
fradj( "récidivant" )
fradj( "récréatif" )
fradj( "récupérable" )
fradj( "récursif" )
fradj( "récusable" )
fradj( "rédactionnel" )
fradj( "rédhibitoire" )
fradj( "réductible" )
fradj( "réduplicatif" )
fradj( "réelle" )
fradj( "réformable" )
fradj( "réfractaire" )
fradj( "réfutable" )
fradj( "référentiel" )
fradj( "régalien" )
fradj( "réglable" )
fradj( "réglementaire" )
fradj( "régressif" )
fradj( "régulier" )
fradj( "régénérateur" )
fradj( "rémunérateur" )
fradj( "répondante" )
fradj( "répressible" )
fradj( "répressif" )
fradj( "réprobateur" )
fradj( "répulsif" )
fradj( "répétitif" )
fradj( "résidentiel" )
fradj( "résiduaire" )
fradj( "résiduel" )
fradj( "résiduelle" )
fradj( "résiliable" )
fradj( "résinifère" )
fradj( "résistible" )
fradj( "réticent" )
fradj( "rétif" )
fradj( "rétractile" )
fradj( "rétroactif" )
fradj( "rétrospectif" )
fradj( "réversible" )
fradj( "révocable" )
fradj( "révolu" )
fradj( "révélateur" )
fradj( "révérencieux" )
fradj( "rêche" )
fradj( "rêveur" )
fradj( "sablonneux" )
fradj( "sacrificatoire" )
fradj( "sacrificiel" )
fradj( "sacro-saint" )
fradj( "sagace" )
fradj( "sahélien" )
fradj( "saigneux" )
fradj( "sain" )
fradj( "saine" )
fradj( "saisissable" )
fradj( "salace" )
fradj( "salinier" )
fradj( "salubre" )
fradj( "salutaire" )
fradj( "samaritain" )
fradj( "sanctificateur" )
fradj( "sanglante" )
fradj( "sanguinolent" )
fradj( "sanieux" )
fradj( "sans-souci" )
fradj( "saoul" )
fradj( "sapide" )
fradj( "sarcastique" )
fradj( "sardanapalesque" )
fradj( "sardonique" )
fradj( "sarrasin" )
fradj( "satanique" )
fradj( "saturnien" )
fradj( "saugrenu" )
fradj( "saumâtre" )
fradj( "saur" )
fradj( "sauteur" )
fradj( "sauveur" )
fradj( "savonneux" )
fradj( "savoureux" )
fradj( "scabieux" )
fradj( "scabreux" )
fradj( "scandaleux" )
fradj( "scatologique" )
fradj( "scatophage" )
fradj( "scatophile" )
fradj( "schismatique" )
fradj( "schizophrène" )
fradj( "schématique" )
fradj( "scientifique" )
fradj( "script" )
fradj( "scripturaire" )
fradj( "scrupuleux" )
fradj( "scrutateur" )
fradj( "sculptural" )
fradj( "scénique" )
fradj( "secourable" )
fradj( "sectoriel" )
fradj( "seigneurial" )
fradj( "semi-aride" )
fradj( "semi-fini" )
fradj( "semi-ouvré" )
fradj( "semi-perméable" )
fradj( "semi-public" )
fradj( "semi-publique" )
fradj( "sempiternel" )
fradj( "sempiternelle" )
fradj( "sensibilisateur" )
fradj( "sensuel" )
fradj( "sensée" )
fradj( "sentencieux" )
fradj( "sentimentale" )
fradj( "septentrional" )
fradj( "septentrionale" )
fradj( "septique" )
fradj( "sereine" )
fradj( "serviable" )
fradj( "seulet" )
fradj( "sexiste" )
fradj( "sexuel" )
fradj( "seyant" )
fradj( "sibyllin" )
fradj( "siccatif" )
fradj( "sidéral" )
fradj( "sidérurgique" )
fradj( "sigillé" )
fradj( "signalétique" )
fradj( "significatif" )
fradj( "silicicole" )
fradj( "simien" )
fradj( "simiesque" )
fradj( "similaire" )
fradj( "simplifiable" )
fradj( "simplificateur" )
fradj( "simultané" )
fradj( "simulé" )
fradj( "singulière" )
fradj( "sinoque" )
fradj( "sinueux" )
fradj( "sinusoïdal" )
fradj( "sirupeux" )
fradj( "snob" )
fradj( "snobinard" )
fradj( "sobre" )
fradj( "sociable" )
fradj( "sociologique" )
fradj( "socioprofessionnel" )
fradj( "soi-disant" )
fradj( "soignante" )
fradj( "soigneux" )
fradj( "solennel" )
fradj( "solennelle" )
fradj( "solidaire" )
fradj( "soliste" )
fradj( "somatique" )
fradj( "sommable" )
fradj( "sommital" )
fradj( "somptueux" )
fradj( "songeur" )
fradj( "sorcier" )
fradj( "sordide" )
fradj( "sortable" )
fradj( "soucieux" )
fradj( "souhaitable" )
fradj( "souple" )
fradj( "soupçonneux" )
fradj( "sourcilleux" )
fradj( "sous-cutané" )
fradj( "sous-jacent" )
fradj( "soutenable" )
fradj( "soûlard" )
fradj( "spacieux" )
fradj( "spasmodique" )
fradj( "spatio-temporel" )
fradj( "spectaculaire" )
fradj( "sphérique" )
fradj( "sphéroïdal" )
fradj( "spirite" )
fradj( "spiritualiste" )
fradj( "spiroïdal" )
fradj( "spitant" )
fradj( "splanchnique" )
fradj( "splendide" )
fradj( "spontané" )
fradj( "spontanée" )
fradj( "sporadique" )
fradj( "spumeux" )
fradj( "spécieux" )
fradj( "spécifique" )
fradj( "spéculatif" )
fradj( "squameux" )
fradj( "squamifère" )
fradj( "squelettique" )
fradj( "stagnante" )
fradj( "stellaire" )
fradj( "stercoral" )
fradj( "stimulante" )
fradj( "stipendié" )
fradj( "stomacal" )
fradj( "stoïque" )
fradj( "stratosphérique" )
fradj( "stratégique" )
fradj( "stridulant" )
fradj( "structurel" )
fradj( "studieux" )
fradj( "stupide" )
fradj( "stupéfaite" )
fradj( "stérilisé" )
fradj( "subaquatique" )
fradj( "subdésertique" )
fradj( "subjectifs" )
fradj( "subreptice" )
fradj( "subsidiaire" )
fradj( "substantiel" )
fradj( "subtil" )
fradj( "subtile" )
fradj( "subulé" )
fradj( "suburbain" )
fradj( "subversif" )
fradj( "successible" )
fradj( "successif" )
fradj( "succulente" )
fradj( "sucrier" )
fradj( "sudorifique" )
fradj( "sudorifère" )
fradj( "sudoripare" )
fradj( "suffisante" )
fradj( "suffocant" )
fradj( "suggestif" )
fradj( "sujet" )
fradj( "sulfureux" )
fradj( "superficiel" )
fradj( "superfin" )
fradj( "superflu" )
fradj( "superfétatoire" )
fradj( "superlatif" )
fradj( "superposable" )
fradj( "supersonique" )
fradj( "supplémentaire" )
fradj( "supportable" )
fradj( "supposable" )
fradj( "suprasensible" )
fradj( "supère" )
fradj( "supérieur" )
fradj( "surabondante" )
fradj( "surdéveloppé" )
fradj( "suret" )
fradj( "surette" )
fradj( "surfin" )
fradj( "susceptible" )
fradj( "susmentionné" )
fradj( "susnommé" )
fradj( "suspensif" )
fradj( "suspicieux" )
fradj( "sylvestre" )
fradj( "sylvicole" )
fradj( "sympathique" )
fradj( "symphonique" )
fradj( "symptomatique" )
fradj( "symétrique" )
fradj( "synchronique" )
fradj( "syncrétique" )
fradj( "synonyme" )
fradj( "syntaxique" )
fradj( "synthétique" )
fradj( "sécable" )
fradj( "séculaire" )
fradj( "sédatif" )
fradj( "séduisante" )
fradj( "ségrégatif" )
fradj( "ségrégationniste" )
fradj( "sélecteur" )
fradj( "sélectif" )
fradj( "sépulcral" )
fradj( "séquentiel" )
fradj( "séraphique" )
fradj( "séreux" )
fradj( "sériel" )
fradj( "tacite" )
fradj( "taciturne" )
fradj( "taillable" )
fradj( "tardif" )
fradj( "tatillon" )
fradj( "tautologique" )
fradj( "taxable" )
fradj( "tellurien" )
fradj( "tellurique" )
fradj( "temporaire" )
fradj( "temporel" )
fradj( "temporelle" )
fradj( "temporisateur" )
fradj( "tempéré" )
fradj( "tempétueux" )
fradj( "tenace" )
fradj( "tendancieux" )
fradj( "terminologique" )
fradj( "terrestre" )
fradj( "terreux" )
fradj( "terrier" )
fradj( "testable" )
fradj( "textuel" )
fradj( "thermal" )
fradj( "théorique" )
fradj( "théâtral" )
fradj( "tinctorial" )
fradj( "titanesque" )
fradj( "titanique" )
fradj( "tiède" )
fradj( "tiédasse" )
fradj( "tolérants" )
fradj( "tombal" )
fradj( "tombante" )
fradj( "tomenteux" )
fradj( "tonicardiaque" )
fradj( "tonitruante" )
fradj( "tonnant" )
fradj( "topographique" )
fradj( "torpide" )
fradj( "torrentiel" )
fradj( "torrentielle" )
fradj( "torrentueux" )
fradj( "torride" )
fradj( "tortu" )
fradj( "tortueux" )
fradj( "torve" )
fradj( "total" )
fradj( "totalisateur" )
fradj( "totalitaire" )
fradj( "totipotent" )
fradj( "touffu" )
fradj( "touffue" )
fradj( "toulousain" )
fradj( "touranien" )
fradj( "tout-puissant" )
fradj( "toute-puissante" )
fradj( "traceur" )
fradj( "traditionnel" )
fradj( "traditionnelle" )
fradj( "traduisible" )
fradj( "tragique" )
fradj( "traitable" )
fradj( "tranchante" )
fradj( "tranquille" )
fradj( "tranquillisant" )
fradj( "transactionnel" )
fradj( "transactionnelle" )
fradj( "transalpin" )
fradj( "transformable" )
fradj( "transitionnel" )
fradj( "transitoire" )
fradj( "translucide" )
fradj( "transmissible" )
fradj( "transmuable" )
fradj( "transmutable" )
fradj( "transnational" )
fradj( "transposable" )
fradj( "transversal" )
fradj( "trapu" )
fradj( "trapézoïdal" )
fradj( "traversable" )
fradj( "traversier" )
fradj( "tremblotant" )
fradj( "trempé" )
fradj( "triangulaire" )
fradj( "triatomique" )
fradj( "tribal" )
fradj( "tributaire" )
fradj( "tricolore" )
fradj( "trilatéral" )
fradj( "trilingue" )
fradj( "trilobé" )
fradj( "triomphal" )
fradj( "tristounet" )
fradj( "trivial" )
fradj( "trois-points" )
fradj( "tropical" )
fradj( "troupier" )
fradj( "truand" )
fradj( "trémière" )
fradj( "trépidante" )
fradj( "tsigane" )
fradj( "tubaire" )
fradj( "tubulaire" )
fradj( "tubuleux" )
fradj( "tubuliflore" )
fradj( "tudesque" )
fradj( "tumulaire" )
fradj( "tumultueux" )
fradj( "turbide" )
fradj( "turbulente" )
fradj( "turgide" )
fradj( "turpide" )
fradj( "tutélaire" )
fradj( "tyrannique" )
fradj( "télématique" )
fradj( "ténu" )
fradj( "tétrasyllabe" )
fradj( "ultime" )
fradj( "ultramoderne" )
fradj( "ultramontain" )
fradj( "ultrasonique" )
fradj( "ultrasonore" )
fradj( "ultérieur" )
fradj( "unanime" )
fradj( "unicellulaire" )
fradj( "unicolore" )
fradj( "unidirectionnelle" )
fradj( "unilatéral" )
fradj( "unilingue" )
fradj( "uniques" )
fradj( "universaliste" )
fradj( "universel" )
fradj( "universitaire" )
fradj( "univitellin" )
fradj( "univoque" )
fradj( "unième" )
fradj( "urbain" )
fradj( "urcéolé" )
fradj( "urgente" )
fradj( "urogénital" )
fradj( "uropygial" )
fradj( "usager" )
fradj( "usuel" )
fradj( "usuelle" )
fradj( "usufructuaire" )
fradj( "usufruitier" )
fradj( "usuraire" )
fradj( "usurpateur" )
fradj( "usurpatoire" )
fradj( "utilisable" )
fradj( "utilitaire" )
fradj( "utopique" )
fradj( "utopiste" )
fradj( "utriculeux" )
fradj( "utérin" )
fradj( "vaillant" )
fradj( "vain" )
fradj( "vaine" )
fradj( "valable" )
fradj( "valeureux" )
fradj( "valétudinaire" )
fradj( "vanné" )
fradj( "vantard" )
fradj( "vaporeux" )
fradj( "vaseux" )
fradj( "vasouillard" )
fradj( "vaticinateur" )
fradj( "vaudevillesque" )
fradj( "veineux" )
fradj( "velouteux" )
fradj( "velu" )
fradj( "velue" )
fradj( "vendable" )
fradj( "vendéen" )
fradj( "venimeux" )
fradj( "venteux" )
fradj( "ventru" )
fradj( "verbal" )
fradj( "verbeux" )
fradj( "verdelet" )
fradj( "verdoyante" )
fradj( "verdâtre" )
fradj( "vergeté" )
fradj( "vermiculaire" )
fradj( "vermiforme" )
fradj( "vermoulu" )
fradj( "vernaculaire" )
fradj( "vert-de-grisé" )
fradj( "vertigineux" )
fradj( "vertueux" )
fradj( "vertébral" )
fradj( "veule" )
fradj( "vexatoire" )
fradj( "vicariant" )
fradj( "victorieux" )
fradj( "vieillot" )
fradj( "vif" )
fradj( "vigoureux" )
fradj( "vil" )
fradj( "vilaine" )
fradj( "violateur" )
fradj( "violâtre" )
fradj( "vipérin" )
fradj( "virale" )
fradj( "vireux" )
fradj( "virginal" )
fradj( "viril" )
fradj( "virilocal" )
fradj( "virtuel" )
fradj( "visqueux" )
fradj( "vital" )
fradj( "vitale" )
fradj( "vitreux" )
fradj( "vivable" )
fradj( "vivificateur" )
fradj( "vivré" )
fradj( "vocal" )
fradj( "volage" )
fradj( "volante" )
fradj( "volatil" )
fradj( "volatilisable" )
fradj( "volcanique" )
fradj( "volubile" )
fradj( "volumineux" )
fradj( "vomitif" )
fradj( "vraie" )
fradj( "végétarien" )
fradj( "végétatif" )
fradj( "véhémente" )
fradj( "vélaire" )
fradj( "véloce" )
fradj( "véniel" )
fradj( "vénusien" )
fradj( "vénéneux" )
fradj( "vénérien" )
fradj( "véreux" )
fradj( "véridique" )
fradj( "vérifiable" )
fradj( "vérificateur" )
fradj( "vétillard" )
fradj( "vétilleux" )
fradj( "vétuste" )
fradj( "zigzagant" )
fradj( "zodiacal" )
fradj( "zoroastrien" )
fradj( "zélateur" )
fradj( "âpre" )
fradj( "ébaubi" )
fradj( "éblouissante" )
fradj( "éblouissants" )
fradj( "éburnéen" )
fradj( "écailleux" )
fradj( "écervelé" )
fradj( "échangeable" )
fradj( "éclairante" )
fradj( "éclatante" )
fradj( "éclatants" )
fradj( "écologique" )
fradj( "économe" )
fradj( "écrasants" )
fradj( "écumante" )
fradj( "écumeux" )
fradj( "édifiante" )
fradj( "éducatif" )
fradj( "édénique" )
fradj( "égalable" )
fradj( "égalisateur" )
fradj( "égalitariste" )
fradj( "égoïste" )
fradj( "égreneur" )
fradj( "égrotant" )
fradj( "éhonté" )
fradj( "éjectable" )
fradj( "élavé" )
fradj( "électif" )
fradj( "électromagnétique" )
fradj( "élogieux" )
fradj( "éloquente" )
fradj( "élusif" )
fradj( "élémentaire" )
fradj( "éléphantesque" )
fradj( "émerillonné" )
fradj( "émotif" )
fradj( "émotionnel" )
fradj( "émotionnelle" )
fradj( "émérite" )
fradj( "énergique" )
fradj( "énergisant" )
fradj( "énigmatique" )
fradj( "énorme" )
fradj( "énumérable" )
fradj( "énumératif" )
fradj( "épaisse" )
fradj( "éperdu" )
fradj( "épicé" )
fradj( "épidermique" )
fradj( "épidémique" )
fradj( "épigrammatique" )
fradj( "épigraphique" )
fradj( "épineux" )
fradj( "épique" )
fradj( "épisodique" )
fradj( "épistolaire" )
fradj( "épizootique" )
fradj( "épuisable" )
fradj( "épuisant" )
fradj( "épuisé" )
fradj( "équestre" )
fradj( "équiangle" )
fradj( "équipotent" )
fradj( "équitables" )
fradj( "équivalente" )
fradj( "éreinté" )
fradj( "érosif" )
fradj( "érotique" )
fradj( "érugineux" )
fradj( "éruptif" )
fradj( "érythémateux" )
fradj( "érémitique" )
fradj( "ésotérique" )
fradj( "étasunien" )
fradj( "éternelle" )
fradj( "éthylique" )
fradj( "éthéré" )
fradj( "éthérée" )
fradj( "étincelante" )
fradj( "étique" )
fradj( "étirable" )
fradj( "étonnante" )
fradj( "étonnants" )
fradj( "étouffante" )
fradj( "étranges" )
fradj( "étudié" )
fradj( "étudiée" )
fradj( "évaluable" )
fradj( "évanescente" )
fradj( "évaporable" )
fradj( "évasif" )
fradj( "éventuelle" )
fradj( "évidente" )
fradj( "évocatoire" )
fradj( "évolutif" )
fradj( "événementiel" )
fradj( "événementielle" )
fradj( "îlien" )
fradj( "grand" )
fradj( "gros" )
fradj( "jeune" )
fradj( "rapide" )
fradj( dernier )
fradj( simple )
fradj( ordinaire )
fradj( frugal )
fradj( suivant )
fradj( noir )
fradj( chaque )
fradj( petit )
fradj( vert )
fradj( calme )
fradj( sombre )
fradj( brun )
fradj( bistre )
fradj( pesant )
fradj( lourd )
fradj( droit )
fradj( général )
fradj( commun )
fradj( nécessaire )
fradj( capital )
fradj( principal )
fradj( juste )
fradj( rouge )
fradj( étrange )
fradj( singulier )
fradj( éclatant )
fradj( connu )
fradj( désert )
fradj( vide )
fradj( creux )
fradj( profond )
fradj( propre )
fradj( net )
fradj( meilleur )
fradj( russe )
fradj( précise )
fradj( exact )
fradj( gauche )
fradj( différent )
fradj( vaste )
fradj( large )
fradj( ample )
fradj( éloigné )
fradj( lointain )
fradj( gris )
fradj( sérieux )
fradj( important )
fradj( grave )
fradj( chaud )
fradj( méchant )
fradj( mauvais )
fradj( joli )
fradj( bref )
fradj( court )
fradj( natale )
fradj( acromial )
fradj( acquisitif )
fradj( actuariel )
fradj( acidophile )
fradj( coi )
fradj( potential )
fradj( heureux )
fradj( compensateur )
fradj( dilatateur )
fradj( inhibiteur )
fradj( investigateur )
fradj( éducateur )
fradj( élévateur )
entry ambigu : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { ambigu ambigus }
FR_GENRE:FEMININE FR_NOMBRE { ambigüe ambigües } // новая орфография
FR_GENRE:FEMININE FR_NOMBRE { ambiguë ambiguës } // старая орфография
}
entry contigu : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { contigu contigus }
FR_GENRE:FEMININE FR_NOMBRE { contiguë contiguës }
}
entry exigu : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { exigu exigus }
FR_GENRE:FEMININE FR_NOMBRE { exigüe exigües }
FR_GENRE:FEMININE FR_NOMBRE { exiguë exiguës }
}
entry doux : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { doux doux }
FR_GENRE:FEMININE FR_NOMBRE { douce douces }
}
entry roux : FR_ADJ
{
FR_GENRE:MASCULINE FR_NOMBRE { roux roux }
FR_GENRE:MASCULINE FR_NOMBRE { rousse rousses }
}
#define Possessive( masculine, feminine, plural ) \
#begin
entry masculine : FR_ADJ
{
FR_NOMBRE:SINGULIER FR_GENRE { masculine feminine }
FR_NOMBRE:PLURIEL FR_GENRE { plural plural }
}
#end
Possessive( mon, ma, mes )
Possessive( ton, ta, tes )
Possessive( notre, notre, notre )
Possessive( votre, votre, votre )
entry son : FR_ADJ
{
FR_NOMBRE:SINGULIER FR_GENRE { son sa }
FR_NOMBRE:PLURIEL FR_GENRE { ses ses }
FR_GENRE:MASCULINE FR_NOMBRE { leur leurs }
}
}
| adamantin - adamantins
| FR_GENRE:MASCULINE FR_NOMBRE { "" "%+S" } | 14,036,519 | [
1,
361,
301,
970,
267,
300,
1261,
301,
970,
2679,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
14583,
67,
16652,
862,
30,
5535,
2312,
1506,
3740,
14583,
67,
50,
1872,
38,
862,
288,
1408,
565,
2213,
15,
55,
6,
289,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x2E3dD5F1E9E3180a64E367B2aCD56B4004039590/sources/PlayerManagement.sol | @dev Feel free to update this as the kind of data fetched from this oracle becomes clearer. | interface IOracle {
pragma solidity ^0.8.4;
import { IPXP } from "./ParagonsDAOPlayerXP.sol";
struct GeneralData {
uint256 pdtPrice;
uint256 minRankForTransfers;
}
struct PDPData {
uint256 pdtCostPerNameChange;
uint256 pdtCostPerRank;
uint256 pxpCostPerRank;
}
}
| 1,876,939 | [
1,
2954,
292,
4843,
358,
1089,
333,
487,
326,
3846,
434,
501,
12807,
628,
333,
20865,
12724,
2424,
264,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
1665,
16873,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
24,
31,
203,
5666,
288,
2971,
60,
52,
289,
628,
25165,
1553,
346,
7008,
18485,
12148,
60,
52,
18,
18281,
14432,
203,
565,
1958,
9544,
751,
288,
203,
3639,
2254,
5034,
4863,
88,
5147,
31,
203,
3639,
2254,
5034,
1131,
12925,
1290,
1429,
18881,
31,
203,
565,
289,
203,
203,
565,
1958,
453,
8640,
751,
288,
203,
3639,
2254,
5034,
4863,
88,
8018,
2173,
461,
3043,
31,
203,
3639,
2254,
5034,
4863,
88,
8018,
2173,
12925,
31,
203,
3639,
2254,
5034,
10318,
84,
8018,
2173,
12925,
31,
203,
565,
289,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract owned {
address public owner;
function owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
contract ISncToken {
function mintTokens(address _to, uint256 _amount);
function totalSupply() constant returns (uint256 totalSupply);
}
contract SunContractIco is owned{
uint256 public startBlock;
uint256 public endBlock;
uint256 public minEthToRaise;
uint256 public maxEthToRaise;
uint256 public totalEthRaised;
address public multisigAddress;
ISncToken sncTokenContract;
mapping (address => bool) presaleContributorAllowance;
uint256 nextFreeParticipantIndex;
mapping (uint => address) participantIndex;
mapping (address => uint256) participantContribution;
bool icoHasStarted;
bool minTresholdReached;
bool icoHasSucessfulyEnded;
uint256 blocksInWeek;
bool ownerHasClaimedTokens;
uint256 lastEthReturnIndex;
mapping (address => bool) hasClaimedEthWhenFail;
event ICOStarted(uint256 _blockNumber);
event ICOMinTresholdReached(uint256 _blockNumber);
event ICOEndedSuccessfuly(uint256 _blockNumber, uint256 _amountRaised);
event ICOFailed(uint256 _blockNumber, uint256 _ammountRaised);
event ErrorSendingETH(address _from, uint256 _amount);
function SunContractIco(uint256 _startBlock, address _multisigAddress) {
blocksInWeek = 4 * 60 * 24 * 7;
startBlock = _startBlock;
endBlock = _startBlock + blocksInWeek * 4;
minEthToRaise = 5000 * 10**18;
maxEthToRaise = 100000 * 10**18;
multisigAddress = _multisigAddress;
}
//
/* User accessible methods */
//
/* Users send ETH and enter the token sale*/
function () payable {
if (msg.value == 0) throw; // Throw if the value is 0
if (icoHasSucessfulyEnded || block.number > endBlock) throw; // Throw if the ICO has ended
if (!icoHasStarted){ // Check if this is the first ICO transaction
if (block.number >= startBlock){ // Check if the ICO should start
icoHasStarted = true; // Set that the ICO has started
ICOStarted(block.number); // Raise ICOStarted event
} else{
throw;
}
}
if (participantContribution[msg.sender] == 0){ // Check if the sender is a new user
participantIndex[nextFreeParticipantIndex] = msg.sender; // Add a new user to the participant index
nextFreeParticipantIndex += 1;
}
if (maxEthToRaise > (totalEthRaised + msg.value)){ // Check if the user sent too much ETH
participantContribution[msg.sender] += msg.value; // Add contribution
totalEthRaised += msg.value;// Add to total eth Raised
sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, msg.value));
if (!minTresholdReached && totalEthRaised >= minEthToRaise){ // Check if the min treshold has been reached one time
ICOMinTresholdReached(block.number); // Raise ICOMinTresholdReached event
minTresholdReached = true; // Set that the min treshold has been reached
}
}else{ // If user sent to much eth
uint maxContribution = maxEthToRaise - totalEthRaised; // Calculate maximum contribution
participantContribution[msg.sender] += maxContribution; // Add maximum contribution to account
totalEthRaised += maxContribution;
sncTokenContract.mintTokens(msg.sender, getSncTokenIssuance(block.number, maxContribution));
uint toReturn = msg.value - maxContribution; // Calculate how much should be returned
icoHasSucessfulyEnded = true; // Set that ICO has successfully ended
ICOEndedSuccessfuly(block.number, totalEthRaised);
if(!msg.sender.send(toReturn)){ // Refund the balance that is over the cap
ErrorSendingETH(msg.sender, toReturn); // Raise event for manual return if transaction throws
}
}
}
/* Users can claim ETH by themselves if they want to in case of ETH failure*/
function claimEthIfFailed(){
if (block.number <= endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO has failed
if (participantContribution[msg.sender] == 0) throw; // Check if user has participated
if (hasClaimedEthWhenFail[msg.sender]) throw; // Check if this account has already claimed ETH
uint256 ethContributed = participantContribution[msg.sender]; // Get participant ETH Contribution
hasClaimedEthWhenFail[msg.sender] = true;
if (!msg.sender.send(ethContributed)){
ErrorSendingETH(msg.sender, ethContributed); // Raise event if send failed, solve manually
}
}
//
/* Only owner methods */
//
/* Adds addresses that are allowed to take part in presale */
function addPresaleContributors(address[] _presaleContributors) onlyOwner {
for (uint cnt = 0; cnt < _presaleContributors.length; cnt++){
presaleContributorAllowance[_presaleContributors[cnt]] = true;
}
}
/* Owner can return eth for multiple users in one call*/
function batchReturnEthIfFailed(uint256 _numberOfReturns) onlyOwner{
if (block.number < endBlock || totalEthRaised >= minEthToRaise) throw; // Check if ICO failed
address currentParticipantAddress;
uint256 contribution;
for (uint cnt = 0; cnt < _numberOfReturns; cnt++){
currentParticipantAddress = participantIndex[lastEthReturnIndex]; // Get next account
if (currentParticipantAddress == 0x0) return; // Check if participants were reimbursed
if (!hasClaimedEthWhenFail[currentParticipantAddress]) { // Check if user has manually recovered ETH
contribution = participantContribution[currentParticipantAddress]; // Get accounts contribution
hasClaimedEthWhenFail[msg.sender] = true; // Set that user got his ETH back
if (!currentParticipantAddress.send(contribution)){ // Send fund back to account
ErrorSendingETH(currentParticipantAddress, contribution); // Raise event if send failed, resolve manually
}
}
lastEthReturnIndex += 1;
}
}
/* Owner sets new address of SunContractToken */
function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
/* Owner can claim reserved tokens on the end of crowsale */
function claimCoreTeamsTokens(address _to) onlyOwner{
if (!icoHasSucessfulyEnded) throw;
if (ownerHasClaimedTokens) throw;
sncTokenContract.mintTokens(_to, sncTokenContract.totalSupply() * 25 / 100);
ownerHasClaimedTokens = true;
}
/* Owner can remove allowance of designated presale contributor */
function removePresaleContributor(address _presaleContributor) onlyOwner {
presaleContributorAllowance[_presaleContributor] = false;
}
/* Set token contract where mints will be done (tokens will be issued)*/
function setTokenContract(address _sncTokenContractAddress) onlyOwner {
sncTokenContract = ISncToken(_sncTokenContractAddress);
}
/* Withdraw funds from contract */
function withdrawEth() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (totalEthRaised < minEthToRaise) throw; // Check if minEthToRaise treshold is exceeded
if(multisigAddress.send(this.balance)){} // Send the contract's balance to multisig address
}
function endIco() onlyOwner {
if (totalEthRaised < minEthToRaise) throw;
if (block.number < endBlock) throw;
icoHasSucessfulyEnded = true;
ICOEndedSuccessfuly(block.number, totalEthRaised);
}
/* Withdraw remaining balance to manually return where contract send has failed */
function withdrawRemainingBalanceForManualRecovery() onlyOwner{
if (this.balance == 0) throw; // Check if there is balance on the contract
if (block.number < endBlock) throw; // Check if ICO failed
if (participantIndex[lastEthReturnIndex] != 0x0) throw; // Check if all the participants have been reimbursed
if (multisigAddress.send(this.balance)){} // Send remainder so it can be manually processed
}
//
/* Getters */
//
function getSncTokenAddress() constant returns(address _tokenAddress){
return address(sncTokenContract);
}
function icoInProgress() constant returns (bool answer){
return icoHasStarted && !icoHasSucessfulyEnded;
}
function isAddressAllowedInPresale(address _querryAddress) constant returns (bool answer){
return presaleContributorAllowance[_querryAddress];
}
function participantContributionInEth(address _querryAddress) constant returns (uint256 answer){
return participantContribution[_querryAddress];
}
function getSncTokenIssuance(uint256 _blockNumber, uint256 _ethSent) constant returns(uint){
if (_blockNumber >= startBlock && _blockNumber < blocksInWeek + startBlock) {
if (presaleContributorAllowance[msg.sender]) return _ethSent * 11600;
else return _ethSent * 11500;
}
if (_blockNumber >= blocksInWeek + startBlock && _blockNumber < blocksInWeek * 2 + startBlock) return _ethSent * 11000;
if (_blockNumber >= blocksInWeek * 2 + startBlock && _blockNumber < blocksInWeek * 3 + startBlock) return _ethSent * 10500;
if (_blockNumber >= blocksInWeek * 3 + startBlock && _blockNumber <= blocksInWeek * 4 + startBlock) return _ethSent * 10000;
}
//
/* This part is here only for testing and will not be included into final version */
//
//function killContract() onlyOwner{
// selfdestruct(msg.sender);
//}
} | Owner sets new address of SunContractToken */ | function changeMultisigAddress(address _newAddress) onlyOwner {
multisigAddress = _newAddress;
}
| 1,752,708 | [
1,
5541,
1678,
394,
1758,
434,
31608,
8924,
1345,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
2549,
5049,
291,
360,
1887,
12,
2867,
389,
2704,
1887,
13,
1338,
5541,
288,
1377,
203,
565,
22945,
360,
1887,
273,
389,
2704,
1887,
31,
203,
225,
289,
27699,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract I4D_Contract{
using SafeMath for uint256;
///////////////////////////////////////////////////////////////////////////////
// Attributes set.
string public name = "I4D";
uint256 public tokenPrice = 0.01 ether;
uint256 public mintax = 0.003 ether; // about 1 USD
uint16[3] public Gate = [10, 100, 1000];
uint8[4] public commissionRate = [1, 2, 3, 4];
uint256 public newPlayerFee=0.1 ether;
bytes32 internal SuperAdmin_id = 0x0eac2ad3c8c41367ba898b18b9f85aab3adac98f5dfc76fafe967280f62987b4;
///////////////////////////////////////////////////////////////////////////////
// Data stored.
uint256 internal administratorETH;
uint256 public totalTokenSupply;
uint256 internal DivsSeriesSum;
mapping(bytes32 => bool) public administrators; // type of byte32, keccak256 of address
mapping(address=>uint256) public tokenBalance;
mapping(address=>address) public highlevel;
mapping(address=>address) public rightbrother;
mapping(address=>address) public leftchild;
mapping(address=>uint256) public deltaDivsSum;
mapping(address=>uint256) public commission;
mapping(address=>uint256) public withdrawETH;
constructor() public{
administrators[SuperAdmin_id] = true;
}
///////////////////////////////////////////////////////////////////////////////
// modifier and Events
modifier onlyAdmin(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
modifier onlyTokenholders() {
require(tokenBalance[msg.sender] > 0);
_;
}
event onEthSell(
address indexed customerAddress,
uint256 ethereumEarned
);
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event testOutput(
uint256 ret
);
event taxOutput(
uint256 tax,
uint256 sumoftax
);
///////////////////////////////////////////////////////////////////////////////
//Administrator api
function withdrawAdministratorETH(uint256 amount)
public
onlyAdmin()
{
address administrator = msg.sender;
require(amount<=administratorETH,"Too much");
administratorETH = administratorETH.sub(amount);
administrator.transfer(amount);
}
function getAdministratorETH()
public
onlyAdmin()
view
returns(uint256)
{
return administratorETH;
}
/** add Adimin here
* you can not change status of super administrator.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdmin()
public
{
require(_identifier!=SuperAdmin_id);
administrators[_identifier] = _status;
}
function setName(string _name)
onlyAdmin()
public
{
name = _name;
}
/////////////////////////////////////////////////////////////////////////////
function setTokenValue(uint256 _value)
onlyAdmin()
public
{
// we may increase our token price.
require(_value > tokenPrice);
tokenPrice = _value;
}
///////////////////////////////////////////////////////////////////////////////
// Player api.
/**
* api of buy tokens.
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
PurchaseTokens(msg.value, _referredBy);
}
/**
* reinvest your profits to puchase more tokens.
*/
function reinvest(uint256 reinvestAmount)
onlyTokenholders()
public
{
require(reinvestAmount>=1,"At least 1 Token!");
address _customerAddress = msg.sender;
require(getReinvestableTokenAmount(_customerAddress)>=reinvestAmount,"You DO NOT have enough ETH!");
withdrawETH[_customerAddress] = withdrawETH[_customerAddress].add(reinvestAmount*tokenPrice);
uint256 tokens = PurchaseTokens(reinvestAmount.mul(tokenPrice), highlevel[_customerAddress]);
///////////////////
emit onReinvestment(_customerAddress,tokens*tokenPrice,tokens);
}
/**
* withdraw the profits(include commissions and divs).
*/
function withdraw(uint256 _amountOfEths)
public
onlyTokenholders()
{
address _customerAddress=msg.sender;
uint256 eth_all = getWithdrawableETH(_customerAddress);
require(eth_all >= _amountOfEths);
withdrawETH[_customerAddress] = withdrawETH[_customerAddress].add(_amountOfEths);
_customerAddress.transfer(_amountOfEths);
emit onEthSell(_customerAddress,_amountOfEths);
//sell logic here
}
// some view functions to get your information.
function getMaxLevel(address _customerAddress, uint16 cur_level)
public
view
returns(uint32)
{
address children = leftchild[_customerAddress];
uint32 maxlvl = cur_level;
while(children!=0x0000000000000000000000000000000000000000){
uint32 child_lvl = getMaxLevel(children, cur_level+1);
if(maxlvl < child_lvl){
maxlvl = child_lvl;
}
children = rightbrother[children];
}
return maxlvl;
}
function getTotalNodeCount(address _customerAddress)
public
view
returns(uint32)
{
uint32 ctr=1;
address children = leftchild[_customerAddress];
while(children!=0x0000000000000000000000000000000000000000){
ctr += getTotalNodeCount(children);
children = rightbrother[children];
}
return ctr;
}
function getMaxProfitAndtoken(address[] playerList)
public
view
returns(uint256[],uint256[],address[])
{
uint256 len=playerList.length;
uint256 i;
uint256 Profit;
uint256 token;
address hl;
uint[] memory ProfitList=new uint[](len);
uint[] memory tokenList=new uint[](len);
address[] memory highlevelList=new address[](len);
for(i=0;i<len;i++)
{
Profit=getTotalProfit(playerList[i]);
token=tokenBalance[playerList[i]];
hl=highlevel[playerList[i]];
ProfitList[i]=Profit;
tokenList[i]=token;
highlevelList[i]=hl;
}
return (ProfitList,tokenList,highlevelList);
}
function getReinvestableTokenAmount(address _customerAddress)
public
view
returns(uint256)
{
return getWithdrawableETH(_customerAddress).div(tokenPrice);
}
/**
* Total profit = your withdrawable ETH + ETHs you have withdrew.
*/
function getTotalProfit(address _customerAddress)
public
view
returns(uint256)
{
return commission[_customerAddress].add(DivsSeriesSum.sub(deltaDivsSum[_customerAddress]).mul(tokenBalance[_customerAddress])/10*3);
}
function getWithdrawableETH(address _customerAddress)
public
view
returns(uint256)
{
uint256 divs = DivsSeriesSum.sub(deltaDivsSum[_customerAddress]).mul(tokenBalance[_customerAddress])/10*3;
return commission[_customerAddress].add(divs).sub(withdrawETH[_customerAddress]);
}
function getTokenBalance()
public
view
returns(uint256)
{
address _address = msg.sender;
return tokenBalance[_address];
}
function getContractBalance()public view returns (uint) {
return address(this).balance;
}
/**
* get your commission rate by your token held.
*/
function getCommissionRate(address _customerAddress)
public
view
returns(uint8)
{
if(tokenBalance[_customerAddress]<1){
return 0;
}
uint8 i;
for(i=0; i<Gate.length; i++){
if(tokenBalance[_customerAddress]<Gate[i]){
break;
}
}
return commissionRate[i];
}
///////////////////////////////////////////////////////////////////////////////
// functions to calculate commissions and divs when someone purchase some tokens.
/**
* api for buying tokens.
*/
function PurchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
/////////////////////////////////
address _customerAddress=msg.sender;
uint256 numOfToken;
require(_referredBy==0x0000000000000000000000000000000000000000 || tokenBalance[_referredBy] > 0);
if(tokenBalance[_customerAddress] > 0)
{
require(_incomingEthereum >= tokenPrice,"ETH is NOT enough");
require(_incomingEthereum % tokenPrice ==0);
require(highlevel[_customerAddress] == _referredBy);
numOfToken = ETH2Tokens(_incomingEthereum);
}
else
{
//New player without a inviter will be taxed for newPlayerFee, and this value can be changed by administrator
if(_referredBy==0x0000000000000000000000000000000000000000 || _referredBy==_customerAddress)
{
require(_incomingEthereum >= newPlayerFee+tokenPrice,"ETH is NOT enough");
require((_incomingEthereum-newPlayerFee) % tokenPrice ==0);
_incomingEthereum -= newPlayerFee;
numOfToken = ETH2Tokens(_incomingEthereum);
highlevel[_customerAddress] = 0x0000000000000000000000000000000000000000;
administratorETH = administratorETH.add(newPlayerFee);
}
else
{
// new player with invite address.
require(_incomingEthereum >= tokenPrice,"ETH is NOT enough");
require(_incomingEthereum % tokenPrice ==0);
numOfToken = ETH2Tokens(_incomingEthereum);
highlevel[_customerAddress] = _referredBy;
addMember(_referredBy,_customerAddress);
}
commission[_customerAddress] = 0;
}
calDivs(_customerAddress,numOfToken);
calCommission(_incomingEthereum,_customerAddress);
emit onTokenPurchase(_customerAddress,_incomingEthereum,numOfToken,_referredBy);
return numOfToken;
}
/**
* Calculate the dividends of the members hold tokens.
* There are two methods to calculate the dividends.
* We chose the second method for you that you can get more divs.
*/
function calDivs(address customer,uint256 num)
internal
{
// Approach 1.
// Use harmonic series to cal player divs. This is a precise algorithm.
// Approach 2.
// Simplify the "for loop" of approach 1.
// You can get more divs than approach 1 when you buy more than 1 token at one time.
// cal average to avoid overflow.
uint256 average_before = deltaDivsSum[customer].mul(tokenBalance[customer]) / tokenBalance[customer].add(num);
uint256 average_delta = DivsSeriesSum.mul(num) / (num + tokenBalance[customer]);
deltaDivsSum[customer] = average_before.add(average_delta);
DivsSeriesSum = DivsSeriesSum.add(tokenPrice.mul(num) / totalTokenSupply.add(num));
totalTokenSupply += num;
tokenBalance[customer] = num.add(tokenBalance[customer]);
}
/**
* Calculate the commissions of your inviters.
*/
function calCommission(uint256 _incomingEthereum,address _customerAddress)
internal
returns(uint256)
{
address _highlevel=highlevel[_customerAddress];
uint256 tax;
uint256 sumOftax=0;
uint8 i=0;
uint256 tax_chain=_incomingEthereum;
uint256 globalfee = _incomingEthereum.mul(3).div(10);
// The maximum deepth of tree you can get commission is 14. You can never get any eth from your children of more than 15 lvl.
for(i=1; i<=14; i++)
{
if(_highlevel==0x0000000000000000000000000000000000000000 || tokenBalance[_highlevel]==0){
break;
}
uint8 com_rate = getCommissionRate(_highlevel);
tax_chain = tax_chain.mul(com_rate).div(10);
if(tokenBalance[_highlevel]>=Gate[2]){
tax=mul_float_power(_incomingEthereum, i, com_rate, 10);
}
else{
tax=tax_chain;
}
// The minimum deepth of tree you can get commission is 2.
// If the deepth is higher than 2 and the tax is lower than mintax, you can never get any commission.
if(i>2 && tax <= mintax){
break;
}
commission[_highlevel] = commission[_highlevel].add(tax);
sumOftax = sumOftax.add(tax);
_highlevel = highlevel[_highlevel];
emit taxOutput(tax,sumOftax);
}
if(sumOftax.add(globalfee) < _incomingEthereum)
{
administratorETH = _incomingEthereum.sub(sumOftax).sub(globalfee).add(administratorETH);
}
}
/**
* New player with inviter should add member to the group tree.
*/
function addMember(address _referredBy,address _customer)
internal
{
require(tokenBalance[_referredBy] > 0);
if(leftchild[_referredBy]!=0x0000000000000000000000000000000000000000)
{
rightbrother[_customer] = leftchild[_referredBy];
}
leftchild[_referredBy] = _customer;
}
function ETH2Tokens(uint256 _ethereum)
internal
view
returns(uint256)
{
return _ethereum.div(tokenPrice);
}
function Tokens2ETH(uint256 _tokens)
internal
view
returns(uint256)
{
return _tokens.mul(tokenPrice);
}
/**
* Calculate x * (numerator / denominator) ** n
* Use "For Loop" to avoid overflow.
*/
function mul_float_power(uint256 x, uint8 n, uint8 numerator, uint8 denominator)
internal
pure
returns(uint256)
{
uint256 ret = x;
if(x==0 || numerator==0){
return 0;
}
for(uint8 i=0; i<n; i++){
ret = ret.mul(numerator).div(denominator);
}
return ret;
}
}
/**
* @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;
}
} | type of byte32, keccak256 of address
| mapping(bytes32 => bool) public administrators; | 12,601,898 | [
1,
723,
434,
1160,
1578,
16,
417,
24410,
581,
5034,
434,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
3890,
1578,
516,
1426,
13,
1071,
30162,
3062,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// hevm: flattened sources of src/DssSpell.sol
pragma solidity =0.5.12 >0.4.13 >=0.4.23 >=0.5.12;
// https://github.com/dapphub/ds-pause
interface DSPauseAbstract {
function SETOWNER590(address) external; //inject NONSTANDARD NAMING
function SETAUTHORITY631(address) external; //inject NONSTANDARD NAMING
function SETDELAY362(uint256) external; //inject NONSTANDARD NAMING
function PLANS667(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function PROXY384() external view returns (address); //inject NONSTANDARD NAMING
function DELAY460() external view returns (uint256); //inject NONSTANDARD NAMING
function PLOT131(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function DROP945(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING
function EXEC84(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING
}
// https://github.com/makerdao/dss/blob/master/src/jug.sol
interface JugAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function ILKS778(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function VAT142() external view returns (address); //inject NONSTANDARD NAMING
function VOW391() external view returns (address); //inject NONSTANDARD NAMING
function BASE726() external view returns (address); //inject NONSTANDARD NAMING
function INIT893(bytes32) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, address) external; //inject NONSTANDARD NAMING
function DRIP219(bytes32) external returns (uint256); //inject NONSTANDARD NAMING
}
// https://github.com/makerdao/median
interface MedianAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function AGE221() external view returns (uint32); //inject NONSTANDARD NAMING
function WAT475() external view returns (bytes32); //inject NONSTANDARD NAMING
function BAR501() external view returns (uint256); //inject NONSTANDARD NAMING
function ORCL736(address) external view returns (uint256); //inject NONSTANDARD NAMING
function BUD134(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SLOT890(uint8) external view returns (address); //inject NONSTANDARD NAMING
function READ871() external view returns (uint256); //inject NONSTANDARD NAMING
function PEEK743() external view returns (uint256, bool); //inject NONSTANDARD NAMING
function LIFT208(address[] calldata) external; //inject NONSTANDARD NAMING
function DROP945(address[] calldata) external; //inject NONSTANDARD NAMING
function SETBAR416(uint256) external; //inject NONSTANDARD NAMING
function KISS951(address) external; //inject NONSTANDARD NAMING
function DISS455(address) external; //inject NONSTANDARD NAMING
function KISS951(address[] calldata) external; //inject NONSTANDARD NAMING
function DISS455(address[] calldata) external; //inject NONSTANDARD NAMING
function POKE311(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; //inject NONSTANDARD NAMING
}
// https://github.com/makerdao/dss/blob/master/src/spot.sol
interface SpotAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING
function VAT142() external view returns (address); //inject NONSTANDARD NAMING
function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function POKE311(bytes32) external; //inject NONSTANDARD NAMING
function CAGE3() external; //inject NONSTANDARD NAMING
}
// https://github.com/makerdao/dss/blob/master/src/vat.sol
interface VatAbstract {
function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING
function RELY664(address) external; //inject NONSTANDARD NAMING
function DENY283(address) external; //inject NONSTANDARD NAMING
function CAN343(address, address) external view returns (uint256); //inject NONSTANDARD NAMING
function HOPE769(address) external; //inject NONSTANDARD NAMING
function NOPE162(address) external; //inject NONSTANDARD NAMING
function ILKS778(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING
function URNS690(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING
function GEM16(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING
function DAI867(address) external view returns (uint256); //inject NONSTANDARD NAMING
function SIN509(address) external view returns (uint256); //inject NONSTANDARD NAMING
function DEBT851() external view returns (uint256); //inject NONSTANDARD NAMING
function VICE72() external view returns (uint256); //inject NONSTANDARD NAMING
function LINE452() external view returns (uint256); //inject NONSTANDARD NAMING
function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING
function INIT893(bytes32) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING
function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING
function CAGE3() external; //inject NONSTANDARD NAMING
function SLIP467(bytes32, address, int256) external; //inject NONSTANDARD NAMING
function FLUX370(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING
function MOVE182(address, address, uint256) external; //inject NONSTANDARD NAMING
function FROB273(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function FORK393(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function GRAB4(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING
function HEAL121(uint256) external; //inject NONSTANDARD NAMING
function SUCK524(address, address, uint256) external; //inject NONSTANDARD NAMING
function FOLD129(bytes32, address, int256) external; //inject NONSTANDARD NAMING
}
// Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
// TODO: add to dss-interfaces?
interface GemJoin6Like {
function SETIMPLEMENTATION850(address, uint256) external; //inject NONSTANDARD NAMING
}
contract SpellAction {
// MAINNET ADDRESSES
//
// The contracts in this list should correspond to MCD core contracts, verify
// against the current release list at:
// https://changelog.makerdao.com/releases/mainnet/1.1.1/contracts.json
address constant mcd_join_tusd_a973 = 0x4454aF7C8bb9463203b66C816220D41ED7837f44; //inject NONSTANDARD NAMING
address constant mcd_jug931 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING
address constant mcd_spot639 = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; //inject NONSTANDARD NAMING
address constant mcd_vat427 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING
address constant tusd_impl_new757 = 0x7a9701453249e84fd0D5AfE5951e9cBe9ed2E90f; //inject NONSTANDARD NAMING
address constant median_manausd649 = 0x681c4F8f69cF68852BAd092086ffEaB31F5B812c; //inject NONSTANDARD NAMING
address constant gitcoin_feed_old89 = 0xA4188B523EccECFbAC49855eB52eA0b55c4d56dd; //inject NONSTANDARD NAMING
address constant gitcoin_feed_new879 = 0x77EB6CF8d732fe4D92c427fCdd83142DB3B742f7; //inject NONSTANDARD NAMING
// Decimals & precision
uint256 constant thousand409 = 10 ** 3; //inject NONSTANDARD NAMING
uint256 constant million93 = 10 ** 6; //inject NONSTANDARD NAMING
uint256 constant wad294 = 10 ** 18; //inject NONSTANDARD NAMING
uint256 constant ray683 = 10 ** 27; //inject NONSTANDARD NAMING
uint256 constant rad264 = 10 ** 45; //inject NONSTANDARD NAMING
// Many of the settings that change weekly rely on the rate accumulator
// described at https://docs.makerdao.com/smart-contract-modules/rates-module
// To check this yourself, use the following rate calculation (example 8%):
//
// $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )'
//
uint256 constant four_pct_rate701 = 1000000001243680656318820312; //inject NONSTANDARD NAMING
uint256 constant eight_pct_rate301 = 1000000002440418608258400030; //inject NONSTANDARD NAMING
uint256 constant twelve_pct_rate857 = 1000000003593629043335673582; //inject NONSTANDARD NAMING
uint256 constant fifty_pct_rate325 = 1000000012857214317438491659; //inject NONSTANDARD NAMING
function EXECUTE44() external { //inject NONSTANDARD NAMING
// Set the global debt ceiling to 1,196,000,000
// 948 (current DC) + 200 (USDC-A increase) + 48 (TUSD-A increase)
VatAbstract(mcd_vat427).FILE40("Line", 1196 * million93 * rad264);
// Set the USDC-A debt ceiling
//
// Existing debt ceiling: 200 million
// New debt ceiling: 400 million
VatAbstract(mcd_vat427).FILE40("USDC-A", "line", 400 * million93 * rad264);
// Set the TUSD-A debt ceiling
//
// Existing debt ceiling: 2 million
// New debt ceiling: 50 million
VatAbstract(mcd_vat427).FILE40("TUSD-A", "line", 50 * million93 * rad264);
// Set USDC-A collateralization ratio
//
// Existing ratio: 103%
// New ratio: 101%
SpotAbstract(mcd_spot639).FILE40("USDC-A", "mat", 101 * ray683 / 100); // 101% coll. ratio
SpotAbstract(mcd_spot639).POKE311("USDC-A");
// Set TUSD-A collateralization ratio
//
// Existing ratio: 120%
// New ratio: 101%
SpotAbstract(mcd_spot639).FILE40("TUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio
SpotAbstract(mcd_spot639).POKE311("TUSD-A");
// Set PAXUSD-A collateralization ratio
//
// Existing ratio: 103%
// New ratio: 101%
SpotAbstract(mcd_spot639).FILE40("PAXUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio
SpotAbstract(mcd_spot639).POKE311("PAXUSD-A");
// Set the BAT-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("BAT-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("BAT-A", "duty", four_pct_rate701);
// Set the USDC-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("USDC-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("USDC-A", "duty", four_pct_rate701);
// Set the USDC-B stability fee
//
// Previous: 48%
// New: 50%
JugAbstract(mcd_jug931).DRIP219("USDC-B"); // drip right before
JugAbstract(mcd_jug931).FILE40("USDC-B", "duty", fifty_pct_rate325);
// Set the WBTC-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701);
// Set the TUSD-A stability fee
//
// Previous: 0%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("TUSD-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("TUSD-A", "duty", four_pct_rate701);
// Set the KNC-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("KNC-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("KNC-A", "duty", four_pct_rate701);
// Set the ZRX-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("ZRX-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("ZRX-A", "duty", four_pct_rate701);
// Set the MANA-A stability fee
//
// Previous: 10%
// New: 12%
JugAbstract(mcd_jug931).DRIP219("MANA-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("MANA-A", "duty", twelve_pct_rate857);
// Set the USDT-A stability fee
//
// Previous: 6%
// New: 8%
JugAbstract(mcd_jug931).DRIP219("USDT-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("USDT-A", "duty", eight_pct_rate301);
// Set the PAXUSD-A stability fee
//
// Previous: 2%
// New: 4%
JugAbstract(mcd_jug931).DRIP219("PAXUSD-A"); // drip right before
JugAbstract(mcd_jug931).FILE40("PAXUSD-A", "duty", four_pct_rate701);
// Whitelist new TUSD implementation
GemJoin6Like(mcd_join_tusd_a973).SETIMPLEMENTATION850(tusd_impl_new757, 1);
// Replace Gitcoin feed key on MANAUSD Oracle
address[] memory drops = new address[](1);
drops[0] = gitcoin_feed_old89;
MedianAbstract(median_manausd649).DROP945(drops);
address[] memory lifts = new address[](1);
lifts[0] = gitcoin_feed_new879;
MedianAbstract(median_manausd649).LIFT208(lifts);
}
}
contract DssSpell {
DSPauseAbstract public pause =
DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3);
address public action;
bytes32 public tag;
uint256 public eta;
bytes public sig;
uint256 public expiration;
bool public done;
// Provides a descriptive tag for bot consumption
// This should be modified weekly to provide a summary of the actions
// Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/9fe29a1704a7885305774bbb31ab04fedd363259/governance/votes/Executive%20vote%20-%20September%2018%2C%202020.md -q -O - 2>/dev/null)"
string constant public description372 = //inject NONSTANDARD NAMING
"2020-09-18 MakerDAO Executive Spell | Hash: 0xe942f72e80295685e39e303f8979560523beae8569daccfcea2f000b14a14abf";
constructor() public {
sig = abi.encodeWithSignature("execute()");
action = address(new SpellAction());
bytes32 _tag;
address _action = action;
assembly { _tag := extcodehash(_action) }
tag = _tag;
expiration = now + 30 days;
}
// modifier officeHours {
// uint day = (now / 1 days + 3) % 7;
// require(day < 5, "Can only be cast on a weekday");
// uint hour = now / 1 hours % 24;
// require(hour >= 14 && hour < 21, "Outside office hours");
// _;
// }
function SCHEDULE830() public { //inject NONSTANDARD NAMING
require(now <= expiration, "This contract has expired");
require(eta == 0, "This spell has already been scheduled");
eta = now + DSPauseAbstract(pause).DELAY460();
pause.PLOT131(action, tag, sig, eta);
}
function CAST998() public { //inject NONSTANDARD NAMING
require(!done, "spell-already-cast");
done = true;
pause.EXEC84(action, tag, sig, eta);
}
} | inject NONSTANDARD NAMING
| function SCHEDULE830() public { | 15,831,614 | [
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,
348,
27395,
28,
5082,
1435,
1071,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x07F172ddb078f82A18fCB722949a2979438f0f02/sources/PIZZABTC.sol | 1% from total supply maxTransactionAmountTxn
| maxTransactionAmount = 210000 * 1e18; | 3,938,630 | [
1,
21,
9,
628,
2078,
14467,
943,
3342,
6275,
13789,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
943,
3342,
6275,
273,
9035,
2787,
380,
404,
73,
2643,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/69/0x9Aa790B92Df04697996379CE27557d63169fAC51/sources/contracts/LiquidityCertificate.sol | * @notice Sets `burnableAt` of a given certificate. @param certificateId The id of the LiquidityCertificate. @param timestamp The time it will become burnable./ | function setBurnableAt(
address spender,
uint certificateId,
uint timestamp
) external onlyLiquidityPool override {
require(_isApprovedOrOwner(spender, certificateId), "certificate does not exist or not owner");
_certificateData[certificateId].burnableAt = timestamp;
emit CertificateDataModified(
certificateId,
_certificateData[certificateId].liquidity,
_certificateData[certificateId].enteredAt,
timestamp
);
}
| 13,239,219 | [
1,
2785,
1375,
70,
321,
429,
861,
68,
434,
279,
864,
4944,
18,
225,
4944,
548,
1021,
612,
434,
326,
511,
18988,
24237,
4719,
18,
225,
2858,
1021,
813,
518,
903,
12561,
18305,
429,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
15268,
321,
429,
861,
12,
203,
565,
1758,
17571,
264,
16,
203,
565,
2254,
4944,
548,
16,
203,
565,
2254,
2858,
203,
225,
262,
3903,
1338,
48,
18988,
24237,
2864,
3849,
288,
203,
565,
2583,
24899,
291,
31639,
1162,
5541,
12,
87,
1302,
264,
16,
4944,
548,
3631,
315,
14108,
1552,
486,
1005,
578,
486,
3410,
8863,
203,
565,
389,
14108,
751,
63,
14108,
548,
8009,
70,
321,
429,
861,
273,
2858,
31,
203,
203,
565,
3626,
6660,
751,
4575,
12,
203,
1377,
4944,
548,
16,
203,
1377,
389,
14108,
751,
63,
14108,
548,
8009,
549,
372,
24237,
16,
203,
1377,
389,
14108,
751,
63,
14108,
548,
8009,
2328,
329,
861,
16,
203,
1377,
2858,
203,
565,
11272,
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
] |
./full_match/84531/0x60dd6724cD3d224049464A4CD7a58e09183DF1f4/sources/contracts/VipCapped.sol | * @notice A basic guest list contract for testing. @dev For a Vyper implementation of this contract containing additional The owner can invite arbitrary guests A guest can be added permissionlessly with proof of inclusion in current merkle set The owner can change the merkle root at any time Merkle-based permission that has been claimed cannot be revoked permissionlessly. Any guests can be revoked by the owner at-will The TVL cap is based on the number of want tokens in the underlying vaults. This can only be made more permissive over time. If decreased, existing TVL is maintained and no deposits are possible until the TVL has gone below the threshold A variant of the yearn AffiliateToken that supports guest list control of deposits A guest list that gates access by merkle root and a TVL cap/ | contract VipCappedGuestListWrapperUpgradeable is OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
address public wrapper;
bytes32 public guestRoot;
uint256 public userDepositCap;
uint256 public totalDepositCap;
mapping(address => bool) public guests;
event ProveInvitation(address indexed account, bytes32 indexed guestRoot);
event SetGuestRoot(bytes32 indexed guestRoot);
event SetUserDepositCap(uint256 cap);
event SetTotalDepositCap(uint256 cap);
function initialize(address wrapper_) public initializer {
__Ownable_init();
wrapper = wrapper_;
}
function setGuests(address[] calldata _guests, bool[] calldata _invited) external onlyOwner {
_setGuests(_guests, _invited);
}
function vaultBalance(address account) public view returns (uint256) {
return BadgerWrapperAPI(wrapper).totalVaultBalance(account);
}
function wrapperBalance(address user) public view returns (uint256) {
return BadgerWrapperAPI(wrapper).totalWrapperBalance(user);
}
function remainingTotalDepositAllowed() public view returns (uint256) {
return totalDepositCap.sub(vaultBalance(wrapper));
}
function remainingUserDepositAllowed(address user) public view returns (uint256) {
return userDepositCap.sub(wrapperBalance(user));
}
function proveInvitation(address account, bytes32[] calldata merkleProof) public {
require(_verifyInvitationProof(account, merkleProof));
address[] memory accounts = new address[](1);
bool[] memory invited = new bool[](1);
accounts[0] = account;
invited[0] = true;
_setGuests(accounts, invited);
emit ProveInvitation(account, guestRoot);
}
function setGuestRoot(bytes32 guestRoot_) external onlyOwner {
guestRoot = guestRoot_;
emit SetGuestRoot(guestRoot);
}
function setUserDepositCap(uint256 cap_) external onlyOwner {
userDepositCap = cap_;
emit SetUserDepositCap(userDepositCap);
}
function setTotalDepositCap(uint256 cap_) external onlyOwner {
totalDepositCap = cap_;
emit SetTotalDepositCap(totalDepositCap);
}
function authorized(address _guest, uint256 _amount, bytes32[] calldata _merkleProof) external view returns (bool) {
bool invited = guests[_guest];
if (!invited && guestRoot == bytes32(0)) {
invited = true;
}
if (!invited && guestRoot != bytes32(0)) {
invited = _verifyInvitationProof(_guest, _merkleProof);
}
if (invited && remainingUserDepositAllowed(_guest) >= _amount && remainingTotalDepositAllowed() >= _amount) {
return true;
return false;
}
}
function authorized(address _guest, uint256 _amount, bytes32[] calldata _merkleProof) external view returns (bool) {
bool invited = guests[_guest];
if (!invited && guestRoot == bytes32(0)) {
invited = true;
}
if (!invited && guestRoot != bytes32(0)) {
invited = _verifyInvitationProof(_guest, _merkleProof);
}
if (invited && remainingUserDepositAllowed(_guest) >= _amount && remainingTotalDepositAllowed() >= _amount) {
return true;
return false;
}
}
function authorized(address _guest, uint256 _amount, bytes32[] calldata _merkleProof) external view returns (bool) {
bool invited = guests[_guest];
if (!invited && guestRoot == bytes32(0)) {
invited = true;
}
if (!invited && guestRoot != bytes32(0)) {
invited = _verifyInvitationProof(_guest, _merkleProof);
}
if (invited && remainingUserDepositAllowed(_guest) >= _amount && remainingTotalDepositAllowed() >= _amount) {
return true;
return false;
}
}
function authorized(address _guest, uint256 _amount, bytes32[] calldata _merkleProof) external view returns (bool) {
bool invited = guests[_guest];
if (!invited && guestRoot == bytes32(0)) {
invited = true;
}
if (!invited && guestRoot != bytes32(0)) {
invited = _verifyInvitationProof(_guest, _merkleProof);
}
if (invited && remainingUserDepositAllowed(_guest) >= _amount && remainingTotalDepositAllowed() >= _amount) {
return true;
return false;
}
}
} else {
function _setGuests(address[] memory _guests, bool[] memory _invited) internal {
require(_guests.length == _invited.length);
for (uint256 i = 0; i < _guests.length; i++) {
if (_guests[i] == address(0)) {
break;
}
guests[_guests[i]] = _invited[i];
}
}
function _setGuests(address[] memory _guests, bool[] memory _invited) internal {
require(_guests.length == _invited.length);
for (uint256 i = 0; i < _guests.length; i++) {
if (_guests[i] == address(0)) {
break;
}
guests[_guests[i]] = _invited[i];
}
}
function _setGuests(address[] memory _guests, bool[] memory _invited) internal {
require(_guests.length == _invited.length);
for (uint256 i = 0; i < _guests.length; i++) {
if (_guests[i] == address(0)) {
break;
}
guests[_guests[i]] = _invited[i];
}
}
function _verifyInvitationProof(address account, bytes32[] calldata merkleProof) internal view returns (bool) {
bytes32 node = keccak256(abi.encodePacked(account));
return MerkleProofUpgradeable.verify(merkleProof, guestRoot, node);
}
}
| 11,515,832 | [
1,
37,
5337,
13051,
666,
6835,
364,
7769,
18,
225,
2457,
279,
776,
8300,
4471,
434,
333,
6835,
4191,
3312,
1021,
3410,
848,
19035,
11078,
13051,
87,
432,
13051,
848,
506,
3096,
4132,
2656,
715,
598,
14601,
434,
26485,
316,
783,
30235,
444,
1021,
3410,
848,
2549,
326,
30235,
1365,
622,
1281,
813,
31827,
17,
12261,
4132,
716,
711,
2118,
7516,
329,
2780,
506,
22919,
4132,
2656,
715,
18,
5502,
13051,
87,
848,
506,
22919,
635,
326,
3410,
622,
17,
20194,
1021,
399,
58,
48,
3523,
353,
2511,
603,
326,
1300,
434,
2545,
2430,
316,
326,
6808,
9229,
87,
18,
1220,
848,
1338,
506,
7165,
1898,
293,
1840,
688,
1879,
813,
18,
971,
23850,
8905,
16,
2062,
399,
58,
48,
353,
11566,
8707,
471,
1158,
443,
917,
1282,
854,
3323,
3180,
326,
399,
58,
48,
711,
22296,
5712,
326,
5573,
432,
5437,
434,
326,
677,
73,
1303,
23906,
330,
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,
776,
625,
4664,
1845,
12978,
682,
3611,
10784,
429,
353,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
203,
565,
1758,
1071,
4053,
31,
203,
203,
565,
1731,
1578,
1071,
13051,
2375,
31,
203,
565,
2254,
5034,
1071,
729,
758,
1724,
4664,
31,
203,
565,
2254,
5034,
1071,
2078,
758,
1724,
4664,
31,
203,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
13051,
87,
31,
203,
203,
565,
871,
1186,
537,
19896,
12,
2867,
8808,
2236,
16,
1731,
1578,
8808,
13051,
2375,
1769,
203,
565,
871,
1000,
12978,
2375,
12,
3890,
1578,
8808,
13051,
2375,
1769,
203,
565,
871,
28112,
758,
1724,
4664,
12,
11890,
5034,
3523,
1769,
203,
565,
871,
1000,
5269,
758,
1724,
4664,
12,
11890,
5034,
3523,
1769,
203,
203,
203,
565,
445,
4046,
12,
2867,
4053,
67,
13,
1071,
12562,
288,
203,
3639,
1001,
5460,
429,
67,
2738,
5621,
203,
3639,
4053,
273,
4053,
67,
31,
203,
565,
289,
203,
203,
565,
445,
444,
12978,
87,
12,
2867,
8526,
745,
892,
389,
18908,
87,
16,
1426,
8526,
745,
892,
389,
5768,
16261,
13,
3903,
1338,
5541,
288,
203,
3639,
389,
542,
12978,
87,
24899,
18908,
87,
16,
389,
5768,
16261,
1769,
203,
565,
289,
203,
203,
565,
445,
9229,
13937,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
6107,
693,
3611,
2557,
12,
8376,
2934,
4963,
12003,
13937,
12,
4631,
1769,
203,
565,
289,
203,
203,
565,
445,
4053,
13937,
12,
2867,
2
] |
./full_match/43113/0xAadc018F6c102407e30Bd2c65eC372Dad345297c/sources/contracts/PredictionV1.sol | * @notice Set minBetAmount @dev Callable by admin/ | function setMinBetAmount(uint256 _minBetAmount) external whenPaused onlyAdmin {
require(_minBetAmount != 0, "must be superior to 0" );
minBetAmount = _minBetAmount;
emit NewMinBetAmount(currentEpoch, minBetAmount);
}
| 13,166,531 | [
1,
694,
1131,
38,
278,
6275,
225,
10464,
635,
3981,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
27724,
38,
278,
6275,
12,
11890,
5034,
389,
1154,
38,
278,
6275,
13,
3903,
1347,
28590,
1338,
4446,
288,
203,
3639,
2583,
24899,
1154,
38,
278,
6275,
480,
374,
16,
315,
11926,
506,
2240,
9659,
358,
374,
6,
11272,
203,
3639,
1131,
38,
278,
6275,
273,
389,
1154,
38,
278,
6275,
31,
203,
203,
3639,
3626,
1166,
2930,
38,
278,
6275,
12,
2972,
14638,
16,
1131,
38,
278,
6275,
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
] |
./partial_match/1/0xbaDb714559EE40dEc7E28AD33c500B3a87dD8B42/sources/contracts/JUNIQUE_POP_Genesis_Collection.sol | Shuffle the leastOwnedIds array | function mint(address to, uint256 id, uint256 amount, uint256 discountTokenId, bytes32[] calldata proof, bytes memory data)
public
payable
{
require(msg.sender == tx.origin || allowContractMints, "No contracts!");
require(checkSaleState(id), "Sale not active");
require(_checkSaleSchedule(saleSchedules[id]), "Not at this time");
require(tokenMaxSupply[id] == 0 || totalSupply(id) + amount <= tokenMaxSupply[id], "Supply exhausted");
require(perWalletMaxTokens[id] == 0 || balanceOf(to,id) + amount <= perWalletMaxTokens[id], "Reached per-wallet limit!");
require(checkForeignTokenLimits(to, amount), "Not enough foreign tokens");
require((merkleRoot == 0 || _verify(_leaf(msg.sender), proof) || _verify(_leaf(to), proof)), "Invalid Merkle proof");
require(discountTokenId <= discountUsed.length, "discountTokenId is out of range");
require(_checkPrice(amount, discountTokenId), "Not enough ETH");
if (id == 0) {
uint256[] memory leastOwnedIds = findLeastOwnedIds(to);
require(leastOwnedIds.length >= amount, "Unreasonable randomization request");
uint256 nounce = amount;
leastOwnedIds = shuffleArray(leastOwnedIds, nounce);
uint256[] memory randomIds = new uint256[](amount);
uint256 uniqueCount = 0;
for (uint256 i = 0; i < amount; i++) {
randomIds[i] = leastOwnedIds[i];
uniqueCount++;
}
require(uniqueCount == amount, "Unable to generate unique token IDs");
uint256[] memory amounts = createArrayWithSameNumber(amount, 1);
incrementMintCount(to, randomIds, amounts);
_mintBatch(to, randomIds, amounts, data);
return;
require(allowNonRandomMinting, "Only random minting");
mintCount[to][id] += amount;
_mint(to, id, amount, data);
}
}
| 4,347,878 | [
1,
1555,
10148,
326,
4520,
5460,
329,
2673,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
2867,
358,
16,
2254,
5034,
612,
16,
2254,
5034,
3844,
16,
2254,
5034,
12137,
1345,
548,
16,
1731,
1578,
8526,
745,
892,
14601,
16,
1731,
3778,
501,
13,
203,
565,
1071,
203,
565,
8843,
429,
203,
565,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
2229,
18,
10012,
747,
1699,
8924,
49,
28142,
16,
315,
2279,
20092,
4442,
1769,
203,
3639,
2583,
12,
1893,
30746,
1119,
12,
350,
3631,
315,
30746,
486,
2695,
8863,
203,
3639,
2583,
24899,
1893,
30746,
6061,
12,
87,
5349,
27073,
63,
350,
65,
3631,
315,
1248,
622,
333,
813,
8863,
203,
3639,
2583,
12,
2316,
2747,
3088,
1283,
63,
350,
65,
422,
374,
747,
2078,
3088,
1283,
12,
350,
13,
397,
3844,
1648,
1147,
2747,
3088,
1283,
63,
350,
6487,
315,
3088,
1283,
24948,
8863,
203,
3639,
2583,
12,
457,
16936,
2747,
5157,
63,
350,
65,
422,
374,
747,
11013,
951,
12,
869,
16,
350,
13,
397,
3844,
1648,
1534,
16936,
2747,
5157,
63,
350,
6487,
315,
23646,
1534,
17,
19177,
1800,
4442,
1769,
203,
3639,
2583,
12,
1893,
7816,
1345,
12768,
12,
869,
16,
3844,
3631,
315,
1248,
7304,
5523,
2430,
8863,
203,
3639,
2583,
12443,
6592,
15609,
2375,
422,
374,
747,
389,
8705,
24899,
12070,
12,
3576,
18,
15330,
3631,
14601,
13,
747,
389,
8705,
24899,
12070,
12,
869,
3631,
14601,
13,
3631,
315,
1941,
31827,
14601,
8863,
203,
3639,
2583,
12,
23650,
1345,
548,
1648,
12137,
6668,
18,
2469,
16,
315,
23650,
1345,
548,
353,
596,
434,
1048,
8863,
203,
2
] |
pragma solidity >=0.4.22 <0.6.0;
import "./Cuts.sol";
import "./Cell.sol";
import "./Layers.sol";
import "./GoldClaim.sol";
import "./helperFunctions.sol";
import "./auction.sol";
import "./ClaimLocationManager.sol";
contract GoldCrush { //claim management
uint indexOfClaims; //just to keep track of amount of claims, claim id is now claim address
uint totalGoldDust;
uint goldBarsMinted;
address parent;
address auctionHouse;
ClaimLocationManager clm;
Auction c;
mapping(address => GoldClaim) allClaimsIdToAddress;
mapping(uint => address) ownerOfClaim;
mapping(address => address) _ownerOfClaim;
mapping(address => uint) GoldClaimAddressToClaimId;
mapping(address => bool) isGoldClaim;
//mapping(address => uint) AllClaimsToClaimId;
// mapping(uint => address) FromClaimIdToClaimAddress;
GoldClaim[] public goldClaimsArray;
// address[] public claimOwnersArray;
constructor () public {
// parent = msg.sender;
}
function setAuctionHouse (address auctionhouse) public { //should not be public or have acces modifier
auctionHouse = auctionhouse;
c = Auction(auctionhouse);
}
function createNewClaimForAuction (string memory name) public returns (uint) { // creates a new goldClaim contract on the blockchain and returns the address of it.
indexOfClaims++; //id should be address again
GoldClaim newGoldClaim = new GoldClaim(msg.sender, name, auctionHouse, address(clm));
address adresOfClaim = newGoldClaim.getAddress();
// set location;
// uint idOfLocation = newGoldClaim.getLocationObjectAttached();
goldClaimsArray.push(newGoldClaim);
allClaimsIdToAddress[adresOfClaim] = GoldClaim(adresOfClaim);
isGoldClaim[adresOfClaim] = true;
uint auctionNr = c.createNewAuction(adresOfClaim);
return auctionNr;
}
function getAllClaims () public view returns (GoldClaim[] memory) {
return (goldClaimsArray);
}
function checkIfClaim (address claimAddress) public view returns (bool) {
return isGoldClaim[claimAddress];
}
function changeOwnerOfClaim (address claim, address futureOwner) public { // access modifier needed
// erease old values;
uint claimId = GoldClaimAddressToClaimId[claim];
address oldOwner = ownerOfClaim[claimId];
ownerOfClaim[claimId] = futureOwner;
_ownerOfClaim[claim] = futureOwner;
}
function registerAclaim (address _address) public {
require(!isGoldClaim[_address]);
GoldClaim claim = GoldClaim(_address);
indexOfClaims++;
goldClaimsArray.push(claim);
isGoldClaim[_address] = true;
GoldClaimAddressToClaimId[_address] = indexOfClaims;
}
function getClaimInfo (address addressOfClaim) public view returns (int, int, uint) { //location x, location y, numberOfCuts,
int x = allClaimsIdToAddress[addressOfClaim].getLocationX();
int y = allClaimsIdToAddress[addressOfClaim].getLocationY();
uint totalCuts = allClaimsIdToAddress[addressOfClaim].getTotalCutsOnClaim();
return (x, y, totalCuts);
}
function getAddress() public view returns (address) {
return address(this);
}
function setClaimLocManager (address ClaimLocationManagerAddress) public {
clm = ClaimLocationManager(ClaimLocationManagerAddress);
}
} | id should be address again
| indexOfClaims++; | 12,635,683 | [
1,
350,
1410,
506,
1758,
3382,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3133,
15925,
9904,
31,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
// import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// ******************
// this is for staking lp tokens and getting back $pet tokens
// We can use this "MasterChef.sol" conract introduced by SuhiSwap, they do exactly what we need and the code is already used by many smart contracts and battle tested with $100s of millions staked in sushiswap
// *******************
// @TODO maybe lets add the roles library to this also to have more then one wallet being able to run this
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
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_ROLE = 0x00;
/**
* @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 Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index)
public
view
returns (address)
{
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(
hasRole(_roles[role].adminRole, _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 {
require(
hasRole(_roles[role].adminRole, _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 {
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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: contracts/access/Roles.sol
pragma solidity ^0.6.0;
contract Roles is AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR");
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(OPERATOR_ROLE, _msgSender());
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"Roles: caller does not have the MINTER role"
);
_;
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Roles: caller does not have the OPERATOR role"
);
_;
}
}
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// Interface for our erc20 token
interface IMuseToken {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mint(address to, uint256 amount) external;
}
// MasterChef is the master of Sushi. He can make Sushi and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable, Roles {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The Muse TOKEN!
IMuseToken public museToken;
// adding this just in case of nobody using the game but degens hacking the farming
bool devFee = false;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
IMuseToken _museToken,
// address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
museToken = _museToken;
devaddr = msg.sender;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function allowDevFee(bool _allow) public onlyOperator {
devFee = _allow;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOperator {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSushiPerShare: 0
})
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOperator {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return
bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 sushiReward = multiplier
.mul(sushiPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(
sushiReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accSushiPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier
.mul(sushiPerBlock)
.mul(pool.allocPoint)
.div(totalAllocPoint);
//no dev fee as of now
if (devFee) {
museToken.mint(devaddr, sushiReward.div(10));
}
museToken.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(
sushiReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.accSushiPerShare)
.div(1e12)
.sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(
user.rewardDebt
);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = museToken.balanceOf(address(this));
if (_amount > sushiBal) {
museToken.transfer(_to, sushiBal);
} else {
museToken.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
contract MuseToken is ERC20PresetMinterPauser {
// Cap at 1 million
uint256 internal _cap = 1000000 * 10**18;
constructor() public ERC20PresetMinterPauser("Muse", "MUSE") {}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
// change cap in case of decided by the community
function changeCap(uint256 _newCap) external {
require(
hasRole(MINTER_ROLE, _msgSender()),
"ERC20PresetMinterPauser: must have minter role to mint"
);
_cap = _newCap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20PresetMinterPauser) {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) {
// When minting tokens
require(
totalSupply().add(amount) <= _cap,
"ERC20Capped: cap exceeded"
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
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_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 Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _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 {
require(hasRole(_roles[role].adminRole, _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 {
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, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20Pausable is ERC20, Pausable {
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/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.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
pragma solidity ^0.6.2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "./VNFT.sol";
contract PetAirdrop {
event Claimed(uint256 index, address owner);
VNFT public immutable petMinter;
bytes32 public immutable merkleRoot;
// This is a packed array of booleans.
mapping(uint256 => uint256) private claimedBitMap;
constructor(VNFT pet_minter_, bytes32 merkleRoot_) public {
petMinter = pet_minter_;
merkleRoot = merkleRoot_;
}
function isClaimed(uint256 index) public view returns (bool) {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
uint256 claimedWord = claimedBitMap[claimedWordIndex];
uint256 mask = (1 << claimedBitIndex);
return claimedWord & mask == mask;
}
function _setClaimed(uint256 index) private {
uint256 claimedWordIndex = index / 256;
uint256 claimedBitIndex = index % 256;
claimedBitMap[claimedWordIndex] =
claimedBitMap[claimedWordIndex] |
(1 << claimedBitIndex);
}
function claim(uint256 index, bytes32[] calldata merkleProof) external {
require(!isClaimed(index), "MerkleDistributor: Drop already claimed.");
// console.logBytes(abi.encodePacked(index));
// Verify the merkle proof.
bytes32 node = keccak256(abi.encodePacked(bytes32(index)));
// console.logBytes32(node);
require(
MerkleProof.verify(merkleProof, merkleRoot, node),
"MerkleDistributor: Invalid proof."
);
// Mark it claimed and send the token.
_setClaimed(index);
petMinter.mint(msg.sender);
emit Claimed(index, msg.sender);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155Holder.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721Burnable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract TokenRecover is Ownable {
/**
* @dev Remember that only owner can call so be careful when use on contracts generated from other contracts.
* @param tokenAddress The token contract address
* @param tokenAmount Number of tokens to be sent
*/
function recoverERC20(address tokenAddress, uint256 tokenAmount)
public
onlyOwner
{
IERC20(tokenAddress).transfer(owner(), tokenAmount);
}
}
// Interface for our erc20 token
interface IMuseToken {
function totalSupply() external view returns (uint256);
function balanceOf(address tokenOwner)
external
view
returns (uint256 balance);
function allowance(address tokenOwner, address spender)
external
view
returns (uint256 remaining);
function transfer(address to, uint256 tokens)
external
returns (bool success);
function approve(address spender, uint256 tokens)
external
returns (bool success);
function transferFrom(
address from,
address to,
uint256 tokens
) external returns (bool success);
function mintingFinished() external view returns (bool);
function mint(address to, uint256 amount) external;
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
/*
* Deployment checklist::
* 1. Deploy all contracts
* 2. Give minter role to the claiming contract
* 3. Add objects (most basic cost 5 and give 1 day and 1 score)
* 4.
*/
// ERC721,
contract VNFT is
Ownable,
ERC721PresetMinterPauserAutoId,
TokenRecover,
ERC1155Holder
{
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
IMuseToken public muse;
struct VNFTObj {
address token;
uint256 id;
uint256 standard; //the type
}
// Mapping from token ID to NFT struct details
mapping(uint256 => VNFTObj) public vnftDetails;
// max dev allocation is 10% of total supply
uint256 public maxDevAllocation = 100000 * 10**18;
uint256 public devAllocation = 0;
// External NFTs
struct NFTInfo {
address token; // Address of LP token contract.
bool active;
uint256 standard; //the nft standard ERC721 || ERC1155
}
NFTInfo[] public supportedNfts;
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
Counters.Counter private _itemIds;
// how many tokens to burn every time the VNFT is given an accessory, the remaining goes to the community and devs
uint256 public burnPercentage = 90;
uint256 public giveLifePrice = 5 * 10**18;
bool public gameStopped = false;
// mining tokens
mapping(uint256 => uint256) public lastTimeMined;
// VNFT properties
mapping(uint256 => uint256) public timeUntilStarving;
mapping(uint256 => uint256) public vnftScore;
mapping(uint256 => uint256) public timeVnftBorn;
// items/benefits for the VNFT could be anything in the future.
mapping(uint256 => uint256) public itemPrice;
mapping(uint256 => uint256) public itemPoints;
mapping(uint256 => string) public itemName;
mapping(uint256 => uint256) public itemTimeExtension;
// mapping(uint256 => address) public careTaker;
mapping(uint256 => mapping(address => address)) public careTaker;
event BurnPercentageChanged(uint256 percentage);
event ClaimedMiningRewards(uint256 who, address owner, uint256 amount);
event VnftConsumed(uint256 nftId, address giver, uint256 itemId);
event VnftMinted(address to);
event VnftFatalized(uint256 nftId, address killer);
event ItemCreated(uint256 id, string name, uint256 price, uint256 points);
event LifeGiven(address forSupportedNFT, uint256 id);
event Unwrapped(uint256 nftId);
event CareTakerAdded(uint256 nftId, address _to);
event CareTakerRemoved(uint256 nftId);
constructor(address _museToken)
public
ERC721PresetMinterPauserAutoId(
"VNFT",
"VNFT",
"https://gallery.verynify.io/api/"
)
{
_setupRole(OPERATOR_ROLE, _msgSender());
muse = IMuseToken(_museToken);
}
modifier notPaused() {
require(!gameStopped, "Contract is paused");
_;
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Roles: caller does not have the OPERATOR role"
);
_;
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"Roles: caller does not have the MINTER role"
);
_;
}
function contractURI() public pure returns (string memory) {
return "https://gallery.verynifty.io/api";
}
// in case a bug happens or we upgrade to another smart contract
function pauseGame(bool _pause) external onlyOperator {
gameStopped = _pause;
}
// change how much to burn on each buy and how much goes to community.
function changeBurnPercentage(uint256 percentage) external onlyOperator {
require(percentage <= 100);
burnPercentage = burnPercentage;
emit BurnPercentageChanged(burnPercentage);
}
function changeGiveLifePrice(uint256 _newPrice) external onlyOperator {
giveLifePrice = _newPrice * 10**18;
}
function changeMaxDevAllocation(uint256 amount) external onlyOperator {
maxDevAllocation = amount;
}
function itemExists(uint256 itemId) public view returns (bool) {
if (bytes(itemName[itemId]).length > 0) {
return true;
}
}
// check that VNFT didn't starve
function isVnftAlive(uint256 _nftId) public view returns (bool) {
uint256 _timeUntilStarving = timeUntilStarving[_nftId];
if (_timeUntilStarving != 0 && _timeUntilStarving >= block.timestamp) {
return true;
}
}
function getVnftScore(uint256 _nftId) public view returns (uint256) {
return vnftScore[_nftId];
}
function getItemInfo(uint256 _itemId)
public
view
returns (
string memory _name,
uint256 _price,
uint256 _points,
uint256 _timeExtension
)
{
_name = itemName[_itemId];
_price = itemPrice[_itemId];
_timeExtension = itemTimeExtension[_itemId];
_points = itemPoints[_itemId];
}
function getVnftInfo(uint256 _nftId)
public
view
returns (
uint256 _vNFT,
bool _isAlive,
uint256 _score,
uint256 _level,
uint256 _expectedReward,
uint256 _timeUntilStarving,
uint256 _lastTimeMined,
uint256 _timeVnftBorn,
address _owner,
address _token,
uint256 _tokenId,
uint256 _fatalityReward
)
{
_vNFT = _nftId;
_isAlive = this.isVnftAlive(_nftId);
_score = this.getVnftScore(_nftId);
_level = this.level(_nftId);
_expectedReward = this.getRewards(_nftId);
_timeUntilStarving = timeUntilStarving[_nftId];
_lastTimeMined = lastTimeMined[_nftId];
_timeVnftBorn = timeVnftBorn[_nftId];
_owner = this.ownerOf(_nftId);
_token = vnftDetails[_nftId].token;
_tokenId = vnftDetails[_nftId].id;
_fatalityReward = getFatalityReward(_nftId);
}
function editCurves(
uint256 _la,
uint256 _lb,
uint256 _ra,
uint256 _rb
) external onlyOperator {
la = _la;
lb = _lb;
ra = _ra;
lb = _rb;
}
uint256 la = 2;
uint256 lb = 2;
uint256 ra = 6;
uint256 rb = 7;
// get the level the vNFT is on to calculate points
function level(uint256 tokenId) external view returns (uint256) {
// This is the formula L(x) = 2 * sqrt(x * 2)
uint256 _score = vnftScore[tokenId].div(100);
if (_score == 0) {
return 1;
}
uint256 _level = sqrtu(_score.mul(la));
return (_level.mul(lb));
}
// get the level the vNFT is on to calculate the token reward
function getRewards(uint256 tokenId) external view returns (uint256) {
// This is the formula to get token rewards R(level)=(level)*6/7+6
uint256 _level = this.level(tokenId);
if (_level == 1) {
return 6 ether;
}
_level = _level.mul(1 ether).mul(ra).div(rb);
return (_level.add(5 ether));
}
// edit specific item in case token goes up in value and the price for items gets to expensive for normal users.
function editItem(
uint256 _id,
uint256 _price,
uint256 _points,
string calldata _name,
uint256 _timeExtension
) external onlyOperator {
itemPrice[_id] = _price;
itemPoints[_id] = _points;
itemName[_id] = _name;
itemTimeExtension[_id] = _timeExtension;
}
//can mine once every 24 hours per token.
function claimMiningRewards(uint256 nftId) external notPaused {
require(isVnftAlive(nftId), "Your vNFT is dead, you can't mine");
require(
block.timestamp >= lastTimeMined[nftId].add(1 minutes) ||
lastTimeMined[nftId] == 0,
"Current timestamp is over the limit to claim the tokens"
);
require(
ownerOf(nftId) == msg.sender ||
careTaker[nftId][ownerOf(nftId)] == msg.sender,
"You must own the vNFT to claim rewards"
);
//reset last start mined so can't remine and cheat
lastTimeMined[nftId] = block.timestamp;
uint256 _reward = this.getRewards(nftId);
muse.mint(msg.sender, _reward);
emit ClaimedMiningRewards(nftId, msg.sender, _reward);
}
// Buy accesory to the VNFT
function buyAccesory(uint256 nftId, uint256 itemId) external notPaused {
require(itemExists(itemId), "This item doesn't exist");
uint256 amount = itemPrice[itemId];
require(
ownerOf(nftId) == msg.sender ||
careTaker[nftId][ownerOf(nftId)] == msg.sender,
"You must own the vNFT or be a care taker to buy items"
);
// require(isVnftAlive(nftId), "Your vNFT is dead");
uint256 amountToBurn = amount.mul(burnPercentage).div(100);
if (!isVnftAlive(nftId)) {
vnftScore[nftId] = itemPoints[itemId];
timeUntilStarving[nftId] = block.timestamp.add(
itemTimeExtension[itemId]
);
} else {
//recalculate timeUntilStarving.
timeUntilStarving[nftId] = block.timestamp.add(
itemTimeExtension[itemId]
);
vnftScore[nftId] = vnftScore[nftId].add(itemPoints[itemId]);
}
// burn 90% so they go back to community mining and staking, and send 10% to devs
if (devAllocation <= maxDevAllocation) {
devAllocation = devAllocation.add(amount.sub(amountToBurn));
muse.transferFrom(msg.sender, address(this), amount);
// burn 90% of token, 10% stay for dev and community fund
muse.burn(amountToBurn);
} else {
muse.burnFrom(msg.sender, amount);
}
emit VnftConsumed(nftId, msg.sender, itemId);
}
function setBaseURI(string memory baseURI_) public onlyOperator {
_setBaseURI(baseURI_);
}
function mint(address player) public override onlyMinter {
//pet minted has 3 days until it starves at first
timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days);
timeVnftBorn[_tokenIds.current()] = block.timestamp;
vnftDetails[_tokenIds.current()] = VNFTObj(
address(this),
_tokenIds.current(),
721
);
super._mint(player, _tokenIds.current());
_tokenIds.increment();
emit VnftMinted(msg.sender);
}
// kill starverd NFT and get 10% of his points.
function fatality(uint256 _deadId, uint256 _tokenId) external notPaused {
require(
!isVnftAlive(_deadId),
"The vNFT has to be starved to claim his points"
);
vnftScore[_tokenId] = vnftScore[_tokenId].add(
(vnftScore[_deadId].mul(60).div(100))
);
// delete vnftDetails[_deadId];
_burn(_deadId);
emit VnftFatalized(_deadId, msg.sender);
}
// Check how much score you'll get by fatality someone.
function getFatalityReward(uint256 _deadId) public view returns (uint256) {
if (isVnftAlive(_deadId)) {
return 0;
} else {
return (vnftScore[_deadId].mul(50).div(100));
}
}
// add items/accessories
function createItem(
string calldata name,
uint256 price,
uint256 points,
uint256 timeExtension
) external onlyOperator returns (bool) {
_itemIds.increment();
uint256 newItemId = _itemIds.current();
itemName[newItemId] = name;
itemPrice[newItemId] = price * 10**18;
itemPoints[newItemId] = points;
itemTimeExtension[newItemId] = timeExtension;
emit ItemCreated(newItemId, name, price, points);
}
// *****************************
// LOGIC FOR EXTERNAL NFTS
// ****************************
// support an external nft to mine rewards and play
function addNft(address _nftToken, uint256 _type) public onlyOperator {
supportedNfts.push(
NFTInfo({token: _nftToken, active: true, standard: _type})
);
}
function supportedNftLength() external view returns (uint256) {
return supportedNfts.length;
}
function updateSupportedNFT(
uint256 index,
bool _active,
address _address
) public onlyOperator {
supportedNfts[index].active = _active;
supportedNfts[index].token = _address;
}
// aka WRAP: lets give life to your erc721 token and make it fun to mint $muse!
function giveLife(
uint256 index,
uint256 _id,
uint256 nftType
) external notPaused {
uint256 amountToBurn = giveLifePrice.mul(burnPercentage).div(100);
if (devAllocation <= maxDevAllocation) {
devAllocation = devAllocation.add(giveLifePrice.sub(amountToBurn));
muse.transferFrom(msg.sender, address(this), giveLifePrice);
// burn 90% of token, 10% stay for dev and community fund
muse.burn(amountToBurn);
} else {
muse.burnFrom(msg.sender, giveLifePrice);
}
if (nftType == 721) {
IERC721(supportedNfts[index].token).transferFrom(
msg.sender,
address(this),
_id
);
} else if (nftType == 1155) {
IERC1155(supportedNfts[index].token).safeTransferFrom(
msg.sender,
address(this),
_id,
1, //the amount of tokens to transfer which always be 1
"0x0"
);
}
// mint a vNFT
vnftDetails[_tokenIds.current()] = VNFTObj(
supportedNfts[index].token,
_id,
nftType
);
timeUntilStarving[_tokenIds.current()] = block.timestamp.add(3 days);
timeVnftBorn[_tokenIds.current()] = block.timestamp;
super._mint(msg.sender, _tokenIds.current());
_tokenIds.increment();
emit LifeGiven(supportedNfts[index].token, _id);
}
// unwrap your vNFT if it is not dead, and get back your original NFT
function unwrap(uint256 _vnftId) external {
require(isVnftAlive(_vnftId), "Your vNFT is dead, you can't unwrap it");
transferFrom(msg.sender, address(this), _vnftId);
VNFTObj memory details = vnftDetails[_vnftId];
timeUntilStarving[_vnftId] = 1;
vnftScore[_vnftId] = 0;
emit Unwrapped(_vnftId);
_withdraw(details.id, details.token, msg.sender, details.standard);
}
// withdraw dead wrapped NFTs or send them to the burn address.
function withdraw(
uint256 _id,
address _contractAddr,
address _to,
uint256 _type
) external onlyOperator {
_withdraw(_id, _contractAddr, _to, _type);
}
function _withdraw(
uint256 _id,
address _contractAddr,
address _to,
uint256 _type
) internal {
if (_type == 1155) {
IERC1155(_contractAddr).safeTransferFrom(
address(this),
_to,
_id,
1,
""
);
} else if (_type == 721) {
IERC721(_contractAddr).transferFrom(address(this), _to, _id);
}
}
// add care taker so in the future if vNFTs are sent to tokenizing platforms like niftex we can whitelist and the previous owner could still mine and do interesting stuff.
function addCareTaker(uint256 _tokenId, address _careTaker) external {
require(
hasRole(OPERATOR_ROLE, _msgSender()) ||
ownerOf(_tokenId) == msg.sender,
"Roles: caller does not have the OPERATOR role"
);
careTaker[_tokenId][msg.sender] = _careTaker;
emit CareTakerAdded(_tokenId, _careTaker);
}
function clearCareTaker(uint256 _tokenId) external {
require(
hasRole(OPERATOR_ROLE, _msgSender()) ||
ownerOf(_tokenId) == msg.sender,
"Roles: caller does not have the OPERATOR role"
);
delete careTaker[_tokenId][msg.sender];
emit CareTakerRemoved(_tokenId);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu(uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128(r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping (uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = 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 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 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 returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(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);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @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.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(address, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC1155Receiver.sol";
import "../../introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
constructor() public {
_registerInterface(
ERC1155Receiver(0).onERC1155Received.selector ^
ERC1155Receiver(0).onERC1155BatchReceived.selector
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC721.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../utils/Counters.sol";
import "../token/ERC721/ERC721.sol";
import "../token/ERC721/ERC721Burnable.sol";
import "../token/ERC721/ERC721Pausable.sol";
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC721PresetMinterPauserAutoId is Context, AccessControl, ERC721Burnable, ERC721Pausable {
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter private _tokenIdTracker;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
constructor(string memory name, string memory symbol, string memory baseURI) public ERC721(name, symbol) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
_setBaseURI(baseURI);
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override(ERC721, ERC721Pausable) {
super._beforeTokenTransfer(from, to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721Pausable is ERC721, Pausable {
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
}
pragma solidity ^0.6.2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/introspection/IERC165.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
contract Roles is AccessControl {
bytes32 public constant MINTER_ROLE = keccak256("MINTER");
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR");
constructor() public {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(OPERATOR_ROLE, _msgSender());
}
modifier onlyMinter() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"Roles: caller does not have the MINTER role"
);
_;
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
"Roles: caller does not have the OPERATOR role"
);
_;
}
}
interface IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
function mint(address to) external;
}
// Stake to get vnfts
contract StakeForVnfts is Roles {
using SafeMath for uint256;
IERC20 public museToken;
IERC721 public vNFT;
// min $muse amount required to stake
uint256 public minStake = 5 * 10**18;
// amount of points needed to redeem a vnft, roughly 1 point is given each day;
uint256 public vnftPrice = 5 * 10**18;
uint256 public totalStaked;
mapping(address => uint256) public balance;
mapping(address => uint256) public lastUpdateTime;
mapping(address => uint256) public points;
event Staked(address who, uint256 amount);
event Withdrawal(address who, uint256 amount);
event VnftMinted(address to);
event StakeReqChanged(uint256 newAmount);
event PriceOfvnftChanged(uint256 newAmount);
constructor(address _vNFT, address _museToken) public {
vNFT = IERC721(_vNFT);
museToken = IERC20(_museToken);
}
// changes stake requirement
function changeStakeReq(uint256 _newAmount) external onlyOperator {
minStake = _newAmount;
emit StakeReqChanged(_newAmount);
}
function changePriceOfNFT(uint256 _newAmount) external onlyOperator {
vnftPrice = _newAmount;
emit PriceOfvnftChanged(_newAmount);
}
modifier updateReward(address account) {
if (account != address(0)) {
points[account] = earned(account);
lastUpdateTime[account] = block.timestamp;
}
_;
}
//calculate how many points earned so far, this needs to give roughly 1 point a day per 5 tokens staked?.
function earned(address account) public view returns (uint256) {
uint256 blockTime = block.timestamp;
return
balance[account]
.mul(blockTime.sub(lastUpdateTime[account]).mul(2314814814000))
.div(1e18)
.add(points[account]);
}
function stake(uint256 _amount) external updateReward(msg.sender) {
require(
_amount >= minStake,
"You need to stake at least the min $muse"
);
// transfer tokens to this address to stake them
totalStaked = totalStaked.add(_amount);
balance[msg.sender] = balance[msg.sender].add(_amount);
museToken.transferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
// withdraw part of your stake
function withdraw(uint256 amount) public updateReward(msg.sender) {
require(amount > 0, "Amount can't be 0");
require(totalStaked >= amount);
balance[msg.sender] = balance[msg.sender].sub(amount);
totalStaked = totalStaked.sub(amount);
// transfer erc20 back from the contract to the user
museToken.transfer(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
}
// withdraw all your amount staked
function exit() external {
withdraw(balance[msg.sender]);
}
//redeem a vNFT based on a set points price
function redeem() public updateReward(msg.sender) {
require(
points[msg.sender] >= vnftPrice,
"Not enough points to redeem vNFT"
);
points[msg.sender] = points[msg.sender].sub(vnftPrice);
vNFT.mint(msg.sender);
emit VnftMinted(msg.sender);
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/presets/ERC1155PresetMinterPauser.sol";
contract TestERC1155 is ERC1155PresetMinterPauser {
constructor(string memory uri) public ERC1155PresetMinterPauser(uri) {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC1155/ERC1155.sol";
import "../token/ERC1155/ERC1155Burnable.sol";
import "../token/ERC1155/ERC1155Pausable.sol";
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC1155PresetMinterPauser is Context, AccessControl, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) public ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 id, uint256 amount, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal virtual override(ERC1155, ERC1155Pausable)
{
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../GSN/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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 SafeMath for uint256;
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;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri) public {
_setURI(uri);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @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) external view 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 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
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) {
require(accounts[i] != address(0), "ERC1155: batch balance query for the zero address");
batchBalances[i] = _balances[ids[i]][accounts[i]];
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view 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(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, 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(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
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];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(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 `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` 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 account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, 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 (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
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 `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, 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 account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @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(to).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(to).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
pragma solidity ^0.6.2;
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
pragma solidity ^0.6.0;
import "./ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(address account, uint256 id, uint256 value) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(address account, uint256[] memory ids, uint256[] memory values) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./ERC1155.sol";
import "../../utils/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
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);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/presets/ERC721PresetMinterPauserAutoId.sol";
contract TestERC721 is ERC721PresetMinterPauserAutoId {
constructor()
public
ERC721PresetMinterPauserAutoId("test721", "t721", "google.com")
{}
}
| how many tokens to burn every time the VNFT is given an accessory, the remaining goes to the community and devs | uint256 public burnPercentage = 90;
| 2,553,132 | [
1,
13606,
4906,
2430,
358,
18305,
3614,
813,
326,
776,
50,
4464,
353,
864,
392,
2006,
630,
16,
326,
4463,
13998,
358,
326,
19833,
471,
4461,
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
] | [
1,
1,
1,
1,
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,
2254,
5034,
1071,
18305,
16397,
273,
8566,
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
] |
// File: contracts/saga-genesis/interfaces/IMintManager.sol
pragma solidity 0.4.25;
/**
* @title Mint Manager Interface.
*/
interface IMintManager {
/**
* @dev Return the current minting-point index.
*/
function getIndex() external view returns (uint256);
}
// File: contracts/saga-genesis/interfaces/ISGNTokenManager.sol
pragma solidity 0.4.25;
/**
* @title SGN Token Manager Interface.
*/
interface ISGNTokenManager {
/**
* @dev Get the current SGA worth of a given SGN amount.
* @param _sgnAmount The amount of SGN to convert.
* @return The equivalent amount of SGA.
*/
function convertSgnToSga(uint256 _sgnAmount) external view returns (uint256);
/**
* @dev Exchange SGN for SGA.
* @param _sender The address of the sender.
* @param _sgnAmount The amount of SGN received.
* @return The amount of SGA that the sender is entitled to.
*/
function exchangeSgnForSga(address _sender, uint256 _sgnAmount) external returns (uint256);
/**
* @dev Handle direct SGN transfer.
* @param _sender The address of the sender.
* @param _to The address of the destination account.
* @param _value The amount of SGN to be transferred.
*/
function uponTransfer(address _sender, address _to, uint256 _value) external;
/**
* @dev Handle custodian SGN transfer.
* @param _sender The address of the sender.
* @param _from The address of the source account.
* @param _to The address of the destination account.
* @param _value The amount of SGN to be transferred.
*/
function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external;
/**
* @dev Upon minting of SGN vested in delay.
* @param _value The amount of SGN to mint.
*/
function uponMintSgnVestedInDelay(uint256 _value) external;
}
// File: contracts/saga-genesis/interfaces/ISGNConversionManager.sol
pragma solidity 0.4.25;
/**
* @title SGN Conversion Manager Interface.
*/
interface ISGNConversionManager {
/**
* @dev Compute the SGA worth of a given SGN amount at a given minting-point.
* @param _amount The amount of SGN.
* @param _index The minting-point index.
* @return The equivalent amount of SGA.
*/
function sgn2sga(uint256 _amount, uint256 _index) external view returns (uint256);
}
// File: contracts/saga-genesis/interfaces/ISGNAuthorizationManager.sol
pragma solidity 0.4.25;
/**
* @title SGN Authorization Manager Interface.
*/
interface ISGNAuthorizationManager {
/**
* @dev Determine whether or not a user is authorized to sell SGN.
* @param _sender The address of the user.
* @return Authorization status.
*/
function isAuthorizedToSell(address _sender) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGN to another user.
* @param _sender The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransfer(address _sender, address _target) external view returns (bool);
/**
* @dev Determine whether or not a user is authorized to transfer SGN from one user to another user.
* @param _sender The address of the custodian user.
* @param _source The address of the source user.
* @param _target The address of the target user.
* @return Authorization status.
*/
function isAuthorizedToTransferFrom(address _sender, address _source, address _target) external view returns (bool);
}
// File: contracts/wallet_trading_limiter/interfaces/IWalletsTradingLimiter.sol
pragma solidity 0.4.25;
/**
* @title Wallets Trading Limiter Interface.
*/
interface IWalletsTradingLimiter {
/**
* @dev Increment the limiter value of a wallet.
* @param _wallet The address of the wallet.
* @param _value The amount to be updated.
*/
function updateWallet(address _wallet, uint256 _value) external;
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address is relates to one of the given identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return Is the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
pragma solidity 0.4.25;
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager";
bytes32 internal constant _ISGAToken_ = "ISGAToken" ;
bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender is relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return Is the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: contracts/saga-genesis/SGNTokenManager.sol
pragma solidity 0.4.25;
/**
* Details of usage of licenced software see here: https://www.saga.org/software/readme_v1
*/
/**
* @title SGN Token Manager.
*/
contract SGNTokenManager is ISGNTokenManager, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.0";
event ExchangeSgnForSgaCompleted(address indexed _user, uint256 _input, uint256 _output);
event MintSgnVestedInDelayCompleted(uint256 _value);
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) ContractAddressLocatorHolder(_contractAddressLocator) public {}
/**
* @dev Return the contract which implements the ISGNAuthorizationManager interface.
*/
function getSGNAuthorizationManager() public view returns (ISGNAuthorizationManager) {
return ISGNAuthorizationManager(getContractAddress(_ISGNAuthorizationManager_));
}
/**
* @dev Return the contract which implements the ISGNConversionManager interface.
*/
function getSGNConversionManager() public view returns (ISGNConversionManager) {
return ISGNConversionManager(getContractAddress(_ISGNConversionManager_));
}
/**
* @dev Return the contract which implements the IMintManager interface.
*/
function getMintManager() public view returns (IMintManager) {
return IMintManager(getContractAddress(_IMintManager_));
}
/**
* @dev Return the contract which implements the IWalletsTradingLimiter interface.
*/
function getWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) {
return IWalletsTradingLimiter(getContractAddress(_WalletsTradingLimiter_SGNTokenManager_));
}
/**
* @dev Get the current SGA worth of a given SGN amount.
* @param _sgnAmount The amount of SGN to convert.
* @return The equivalent amount of SGA.
*/
function convertSgnToSga(uint256 _sgnAmount) external view returns (uint256) {
return convertSgnToSgaFunc(_sgnAmount);
}
/**
* @dev Exchange SGN for SGA.
* @param _sender The address of the sender.
* @param _sgnAmount The amount of SGN received.
* @return The amount of SGA that the sender is entitled to.
*/
function exchangeSgnForSga(address _sender, uint256 _sgnAmount) external only(_ISGNToken_) returns (uint256) {
require(getSGNAuthorizationManager().isAuthorizedToSell(_sender), "exchanging SGN for SGA is not authorized");
uint256 sgaAmount = convertSgnToSgaFunc(_sgnAmount);
require(sgaAmount > 0, "returned amount is zero");
emit ExchangeSgnForSgaCompleted(_sender, _sgnAmount, sgaAmount);
return sgaAmount;
}
/**
* @dev Handle direct SGN transfer.
* @param _sender The address of the sender.
* @param _to The address of the destination account.
* @param _value The amount of SGN to be transferred.
*/
function uponTransfer(address _sender, address _to, uint256 _value) external only(_ISGNToken_) {
require(getSGNAuthorizationManager().isAuthorizedToTransfer(_sender, _to), "direct-transfer of SGN is not authorized");
getWalletsTradingLimiter().updateWallet(_to, _value);
_value;
}
/**
* @dev Handle custodian SGN transfer.
* @param _sender The address of the sender.
* @param _from The address of the source account.
* @param _to The address of the destination account.
* @param _value The amount of SGN to be transferred.
*/
function uponTransferFrom(address _sender, address _from, address _to, uint256 _value) external only(_ISGNToken_) {
require(getSGNAuthorizationManager().isAuthorizedToTransferFrom(_sender, _from, _to), "custodian-transfer of SGN is not authorized");
getWalletsTradingLimiter().updateWallet(_to, _value);
_value;
}
/**
* @dev Upon minting of SGN vested in delay.
* @param _value The amount of SGN to mint.
*/
function uponMintSgnVestedInDelay(uint256 _value) external only(_ISGNToken_) {
emit MintSgnVestedInDelayCompleted(_value);
}
/**
* @dev Get the amount of SGA received upon conversion of a given SGN amount.
* @param _sgnAmount the amount of SGN to convert.
* @return The amount of SGA received upon conversion .
*/
function convertSgnToSgaFunc(uint256 _sgnAmount) private view returns (uint256) {
return getSGNConversionManager().sgn2sga(_sgnAmount, getMintManager().getIndex());
}
} | * @dev Return the contract which implements the IWalletsTradingLimiter interface./ | function getWalletsTradingLimiter() public view returns (IWalletsTradingLimiter) {
return IWalletsTradingLimiter(getContractAddress(_WalletsTradingLimiter_SGNTokenManager_));
}
| 2,509,654 | [
1,
990,
326,
6835,
1492,
4792,
326,
467,
26558,
2413,
1609,
7459,
22329,
1560,
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,
565,
445,
13876,
454,
2413,
1609,
7459,
22329,
1435,
1071,
1476,
1135,
261,
45,
26558,
2413,
1609,
7459,
22329,
13,
288,
203,
3639,
327,
467,
26558,
2413,
1609,
7459,
22329,
12,
588,
8924,
1887,
24899,
26558,
2413,
1609,
7459,
22329,
67,
55,
8318,
1345,
1318,
67,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xCA5b0AE1d104030a9B8F879523508EFd86c14483/sources/@animoca/ethereum-contracts/contracts/token/ERC20/ERC20Metadata.sol | @notice Marks the following ERC165 interface(s) as supported: ERC20Metadata. | constructor() {
ERC20MetadataStorage.init();
}
| 17,197,420 | [
1,
20981,
326,
3751,
4232,
39,
28275,
1560,
12,
87,
13,
487,
3260,
30,
4232,
39,
3462,
2277,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
288,
203,
3639,
4232,
39,
3462,
2277,
3245,
18,
2738,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
struct Airline {
string name;
bool isRegistered;
uint256 funds;
}
struct Insuree {
bool isCredited;
uint256 balance;
}
address private contractOwner;
address private appContractOwner;
bool private operational = true;
uint constant airlinesThreshold = 4;
uint256 private airlinesCount = 0;
mapping(address => Airline) private registeredAirlines;
mapping(address => uint256) private multiParty;
mapping(address => address) private votedAirlines;
mapping(bytes32 => address[]) private flightInsurees;
mapping(address => Insuree) private insureesBalance;
mapping(address => bool) private authorizedContracts;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(address firstAirline, string memory name) public
{
contractOwner = msg.sender;
_registerAirline(firstAirline, name);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireAppContractOwner() {
require(msg.sender == appContractOwner, "Caller is not App contract owner");
_;
}
modifier requireIsAuthorized()
{
require(authorizedContracts[msg.sender], "(data contract) Caller is not authorized");
_;
}
/**
* @dev Modifier that requires the Airline be registered
*/
modifier requireRegistredAirline(address airline) {
require(registeredAirlines[airline].isRegistered == true, "Airline is not registered");
_;
}
/**
* @dev Modifier that requires the Airline has funds
*/
modifier requireFundedAirline(address airline) {
require(registeredAirlines[airline].funds >= (10 ether), "Airline has not enough fund");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool)
{
return operational;
}
/**
* Authorize application contract owner calls this contract. Only this address can call
* data contract business methods.
*/
function authorizeCaller(address _appContractOwner) external requireIsOperational requireContractOwner {
appContractOwner = _appContractOwner;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode) external
requireContractOwner requireAppContractOwner
{
require(mode != operational, "New mode must be different from existing one");
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(address airline, string calldata name, address applicantAirline)
external requireIsOperational requireAppContractOwner
requireRegistredAirline(airline) requireFundedAirline(airline) {
if(airlinesCount < airlinesThreshold)
{
_registerAirline(applicantAirline, name);
}
else
{
require(!(votedAirlines[airline] == applicantAirline), "The airline is already voted to applicantAirline");
multiParty[applicantAirline] += 1;
votedAirlines[airline] = applicantAirline;
if(airlinesCount.mod(multiParty[applicantAirline]) == 0 && multiParty[applicantAirline] != 1)
{
_registerAirline(applicantAirline, name);
delete multiParty[applicantAirline];
delete votedAirlines[airline];
}
}
}
function _registerAirline(address airlineAddr, string memory name) private {
Airline memory airline = Airline(name, true, 0);
airlinesCount = airlinesCount + 1;
registeredAirlines[airlineAddr] = airline;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy(address airline, string calldata flight, uint256 timestamp, address insuree)
external payable requireIsOperational requireAppContractOwner {
require(msg.value <= (1 ether), "Value should be less than or equals to one ether");
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flightInsurees[flightKey].push(insuree);
Insuree memory insureeStuct = Insuree(false, msg.value);
insureesBalance[insuree] = insureeStuct;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees(address airline, string calldata flight, uint256 timestamp, uint256 numerator, uint256 denominator)
external requireIsOperational requireAppContractOwner {
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
Insuree memory insuree;
for (uint256 i = 0; i < flightInsurees[flightKey].length; i++) {
insuree = insureesBalance[flightInsurees[flightKey][i]];
uint256 currentBalance = insuree.balance;
uint256 newBalance = currentBalance.mul(numerator).div(denominator);
insuree.isCredited = true;
insuree.balance = newBalance;
insureesBalance[flightInsurees[flightKey][i]] = insuree;
}
delete flightInsurees[flightKey];
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function withdraw(address payable insuree) external requireIsOperational requireAppContractOwner
{
require(insureesBalance[insuree].balance > 0, "Insuree has no balance.");
uint256 value = insureesBalance[insuree].balance;
insureesBalance[insuree].balance = 0;
insuree.transfer(value);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address airline, uint256 value) external payable requireIsOperational requireAppContractOwner
requireRegistredAirline(airline)
{
registeredAirlines[airline].funds = registeredAirlines[airline].funds.add(value);
}
function getFlightKey(address airline, string memory flight, uint256 timestamp) internal pure returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
function getAirline(address airlineAddress) external view requireIsOperational requireAppContractOwner
returns(string memory, bool, uint) {
Airline memory airline = registeredAirlines[airlineAddress];
return (airline.name, airline.isRegistered, airline.funds);
}
function getInsureeBalance(address insuree) external view requireIsOperational
returns(uint256)
{
if(insureesBalance[insuree].isCredited)
return insureesBalance[insuree].balance;
else
return uint256(0);
}
/**
* @dev Fallback function for funding smart contract.
*
*/
fallback() external payable
{
//this.fund{value:msg.value}(msg.sender, msg.value);
}
} | * @dev Modifier that requires the Airline be registered/ | modifier requireRegistredAirline(address airline) {
require(registeredAirlines[airline].isRegistered == true, "Airline is not registered");
_;
}
| 6,353,459 | [
1,
9829,
716,
4991,
326,
432,
481,
1369,
506,
4104,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
2583,
1617,
376,
1118,
29752,
1369,
12,
2867,
23350,
1369,
13,
288,
203,
3639,
2583,
12,
14327,
29752,
3548,
63,
1826,
1369,
8009,
291,
10868,
422,
638,
16,
315,
29752,
1369,
353,
486,
4104,
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
] |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IArchRouterImmutableState.sol';
/// @title Immutable state
/// @notice Immutable state used by periphery contracts
abstract contract ArchRouterImmutableState is IArchRouterImmutableState {
/// @inheritdoc IArchRouterImmutableState
address public immutable override uniV3Factory;
/// @inheritdoc IArchRouterImmutableState
address public immutable override WETH;
constructor(address _uniV3Factory, address _WETH) {
uniV3Factory = _uniV3Factory;
WETH = _WETH;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Copyright 2021 Archer DAO: Chris Piatt ([email protected]).
*/
import './interfaces/IERC20Extended.sol';
import './interfaces/IUniswapV2Pair.sol';
import './interfaces/IUniswapV3Pool.sol';
import './interfaces/IUniV3Router.sol';
import './interfaces/IWETH.sol';
import './lib/RouteLib.sol';
import './lib/TransferHelper.sol';
import './lib/SafeCast.sol';
import './lib/Path.sol';
import './lib/CallbackValidation.sol';
import './ArchRouterImmutableState.sol';
import './PaymentsWithFee.sol';
import './Multicall.sol';
import './SelfPermit.sol';
/**
* @title ArcherSwapRouter
* @dev Allows Uniswap V2/V3 Router-compliant trades to be paid via tips instead of gas
*/
contract ArcherSwapRouter is
IUniV3Router,
ArchRouterImmutableState,
PaymentsWithFee,
Multicall,
SelfPermit
{
using Path for bytes;
using SafeCast for uint256;
/// @dev Used as the placeholder value for amountInCached, because the computed amount in for an exact output swap
/// can never actually be this value
uint256 private constant DEFAULT_AMOUNT_IN_CACHED = type(uint256).max;
/// @dev Transient storage variable used for returning the computed amount in for an exact output swap.
uint256 private amountInCached = DEFAULT_AMOUNT_IN_CACHED;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Trade details
struct Trade {
uint amountIn;
uint amountOut;
address[] path;
address payable to;
uint256 deadline;
}
/// @notice Uniswap V3 Swap Callback
struct SwapCallbackData {
bytes path;
address payer;
}
/**
* @notice Construct new ArcherSwap Router
* @param _uniV3Factory Uni V3 Factory address
* @param _WETH WETH address
*/
constructor(address _uniV3Factory, address _WETH) ArchRouterImmutableState(_uniV3Factory, _WETH) {}
/**
* @notice Swap tokens for ETH and pay amount of ETH as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapExactTokensForETHAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn
);
_exactInputSwap(factory, trade.path, address(this));
uint256 amountOut = IWETH(WETH).balanceOf(address(this));
require(amountOut >= trade.amountOut, 'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
tip(tipAmount);
TransferHelper.safeTransferETH(trade.to, amountOut - tipAmount);
}
/**
* @notice Swap tokens for ETH and pay amount of ETH as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapTokensForExactETHAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
require(trade.path[trade.path.length - 1] == WETH, 'ArchRouter: INVALID_PATH');
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]
);
_exactOutputSwap(factory, amounts, trade.path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
tip(tipAmount);
TransferHelper.safeTransferETH(trade.to, trade.amountOut - tipAmount);
}
/**
* @notice Swap ETH for tokens and pay % of ETH input as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param tipAmount amount of ETH to pay as tip
*/
function swapExactETHForTokensAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
tip(tipAmount);
require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH');
uint256 inputAmount = msg.value - tipAmount;
IWETH(WETH).deposit{value: inputAmount}();
assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), inputAmount));
uint256 balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to);
_exactInputSwap(factory, trade.path, trade.to);
require(
IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut,
'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @notice Swap ETH for tokens and pay amount of ETH input as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param tipAmount amount of ETH to pay as tip
*/
function swapETHForExactTokensAndTipAmount(
address factory,
Trade calldata trade,
uint256 tipAmount
) external payable {
tip(tipAmount);
require(trade.path[0] == WETH, 'ArchRouter: INVALID_PATH');
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
uint256 inputAmount = msg.value - tipAmount;
require(amounts[0] <= inputAmount, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]));
_exactOutputSwap(factory, amounts, trade.path, trade.to);
if (inputAmount > amounts[0]) {
TransferHelper.safeTransferETH(msg.sender, inputAmount - amounts[0]);
}
}
/**
* @notice Swap tokens for tokens and pay ETH amount as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapExactTokensForTokensAndTipAmount(
address factory,
Trade calldata trade
) external payable {
tip(msg.value);
_swapExactTokensForTokens(factory, trade);
}
/**
* @notice Swap tokens for tokens and pay % of tokens as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param pathToEth Path to ETH for tip
* @param tipPct % of resulting tokens to pay as tip
*/
function swapExactTokensForTokensAndTipPct(
address factory,
Trade calldata trade,
address[] calldata pathToEth,
uint32 tipPct
) external payable {
_swapExactTokensForTokens(factory, trade);
IERC20Extended toToken = IERC20Extended(pathToEth[0]);
uint256 contractTokenBalance = toToken.balanceOf(address(this));
uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000;
TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount);
_tipWithTokens(factory, pathToEth);
}
/**
* @notice Swap tokens for tokens and pay ETH amount as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function swapTokensForExactTokensAndTipAmount(
address factory,
Trade calldata trade
) external payable {
tip(msg.value);
_swapTokensForExactTokens(factory, trade);
}
/**
* @notice Swap tokens for tokens and pay % of tokens as tip
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
* @param pathToEth Path to ETH for tip
* @param tipPct % of resulting tokens to pay as tip
*/
function swapTokensForExactTokensAndTipPct(
address factory,
Trade calldata trade,
address[] calldata pathToEth,
uint32 tipPct
) external payable {
_swapTokensForExactTokens(factory, trade);
IERC20Extended toToken = IERC20Extended(pathToEth[0]);
uint256 contractTokenBalance = toToken.balanceOf(address(this));
uint256 tipAmount = (contractTokenBalance * tipPct) / 1000000;
TransferHelper.safeTransfer(pathToEth[0], trade.to, contractTokenBalance - tipAmount);
_tipWithTokens(factory, pathToEth);
}
/**
* @notice Returns the pool for the given token pair and fee. The pool contract may or may not exist.
* @param tokenA First token
* @param tokenB Second token
* @param fee Pool fee
* @return Uniswap V3 Pool
*/
function getPool(
address tokenA,
address tokenB,
uint24 fee
) private view returns (IUniswapV3Pool) {
return IUniswapV3Pool(RouteLib.computeAddress(uniV3Factory, RouteLib.getPoolKey(tokenA, tokenB, fee)));
}
/**
* @notice Uniswap V3 Callback function that validates and pays for trade
* @dev Called by Uni V3 pool contract
* @param amount0Delta Delta for token 0
* @param amount1Delta Delta for token 1
* @param _data Swap callback data
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override {
require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
CallbackValidation.verifyCallback(uniV3Factory, tokenIn, tokenOut, fee);
(bool isExactInput, uint256 amountToPay) =
amount0Delta > 0
? (tokenIn < tokenOut, uint256(amount0Delta))
: (tokenOut < tokenIn, uint256(amount1Delta));
if (isExactInput) {
pay(tokenIn, data.payer, msg.sender, amountToPay);
} else {
// either initiate the next swap or pay
if (data.path.hasMultiplePools()) {
data.path = data.path.skipToken();
_exactOutputInternal(amountToPay, msg.sender, 0, data);
} else {
amountInCached = amountToPay;
tokenIn = tokenOut; // swap in/out because exact output swaps are reversed
pay(tokenIn, data.payer, msg.sender, amountToPay);
}
}
}
/// @inheritdoc IUniV3Router
function exactInputSingle(ExactInputSingleParams calldata params)
public
payable
override
returns (uint256 amountOut)
{
amountOut = _exactInputInternal(
params.amountIn,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenIn, params.fee, params.tokenOut), payer: msg.sender})
);
require(amountOut >= params.amountOutMinimum, 'Too little received');
}
/**
* @notice Performs a single exact input Uni V3 swap and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactInputSingleAndTipAmount(ExactInputSingleParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInputSingle(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactInput(ExactInputParams memory params)
public
payable
override
returns (uint256 amountOut)
{
address payer = msg.sender; // msg.sender pays for the first hop
while (true) {
bool hasMultiplePools = params.path.hasMultiplePools();
// the outputs of prior swaps become the inputs to subsequent ones
params.amountIn = _exactInputInternal(
params.amountIn,
hasMultiplePools ? address(this) : params.recipient, // for intermediate swaps, this contract custodies
0,
SwapCallbackData({
path: params.path.getFirstPool(), // only the first pool in the path is necessary
payer: payer
})
);
// decide whether to continue or terminate
if (hasMultiplePools) {
payer = address(this); // at this point, the caller has paid
params.path = params.path.skipToken();
} else {
amountOut = params.amountIn;
break;
}
}
require(amountOut >= params.amountOutMinimum, 'Too little received');
}
/**
* @notice Performs multiple exact input Uni V3 swaps and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactInputAndTipAmount(ExactInputParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountOut)
{
amountOut = exactInput(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactOutputSingle(ExactOutputSingleParams calldata params)
public
payable
override
returns (uint256 amountIn)
{
// avoid an SLOAD by using the swap return data
amountIn = _exactOutputInternal(
params.amountOut,
params.recipient,
params.sqrtPriceLimitX96,
SwapCallbackData({path: abi.encodePacked(params.tokenOut, params.fee, params.tokenIn), payer: msg.sender})
);
require(amountIn <= params.amountInMaximum, 'Too much requested');
// has to be reset even though we don't use it in the single hop case
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}
/**
* @notice Performs an exact output Uni V3 swap and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactOutputSingleAndTipAmount(ExactOutputSingleParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutputSingle(params);
tip(tipAmount);
}
/// @inheritdoc IUniV3Router
function exactOutput(ExactOutputParams calldata params)
public
payable
override
returns (uint256 amountIn)
{
// it's okay that the payer is fixed to msg.sender here, as they're only paying for the "final" exact output
// swap, which happens first, and subsequent swaps are paid for within nested callback frames
_exactOutputInternal(
params.amountOut,
params.recipient,
0,
SwapCallbackData({path: params.path, payer: msg.sender})
);
amountIn = amountInCached;
require(amountIn <= params.amountInMaximum, 'Too much requested');
amountInCached = DEFAULT_AMOUNT_IN_CACHED;
}
/**
* @notice Performs multiple exact output Uni V3 swaps and tips an amount of ETH
* @param params Swap params
* @param tipAmount Tip amount
*/
function exactOutputAndTipAmount(ExactOutputParams calldata params, uint256 tipAmount)
external
payable
returns (uint256 amountIn)
{
amountIn = exactOutput(params);
tip(tipAmount);
}
/**
* @notice Performs a single exact input Uni V3 swap
* @param amountIn Amount of input token
* @param recipient Recipient of swap result
* @param sqrtPriceLimitX96 Price limit
* @param data Swap callback data
*/
function _exactInputInternal(
uint256 amountIn,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountOut) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenIn, address tokenOut, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0, int256 amount1) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
amountIn.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
return uint256(-(zeroForOne ? amount1 : amount0));
}
/**
* @notice Performs a single exact output Uni V3 swap
* @param amountOut Amount of output token
* @param recipient Recipient of swap result
* @param sqrtPriceLimitX96 Price limit
* @param data Swap callback data
*/
function _exactOutputInternal(
uint256 amountOut,
address recipient,
uint160 sqrtPriceLimitX96,
SwapCallbackData memory data
) private returns (uint256 amountIn) {
// allow swapping to the router address with address 0
if (recipient == address(0)) recipient = address(this);
(address tokenOut, address tokenIn, uint24 fee) = data.path.decodeFirstPool();
bool zeroForOne = tokenIn < tokenOut;
(int256 amount0Delta, int256 amount1Delta) =
getPool(tokenIn, tokenOut, fee).swap(
recipient,
zeroForOne,
-amountOut.toInt256(),
sqrtPriceLimitX96 == 0
? (zeroForOne ? MIN_SQRT_RATIO + 1 : MAX_SQRT_RATIO - 1)
: sqrtPriceLimitX96,
abi.encode(data)
);
uint256 amountOutReceived;
(amountIn, amountOutReceived) = zeroForOne
? (uint256(amount0Delta), uint256(-amount1Delta))
: (uint256(amount1Delta), uint256(-amount0Delta));
// it's technically possible to not receive the full output amount,
// so if no price limit has been specified, require this possibility away
if (sqrtPriceLimitX96 == 0) require(amountOutReceived == amountOut);
}
/**
* @notice Internal implementation of swap tokens for tokens
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function _swapExactTokensForTokens(
address factory,
Trade calldata trade
) internal {
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), trade.amountIn
);
uint balanceBefore = IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to);
_exactInputSwap(factory, trade.path, trade.to);
require(
IERC20Extended(trade.path[trade.path.length - 1]).balanceOf(trade.to) - balanceBefore >= trade.amountOut,
'ArchRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
/**
* @notice Internal implementation of swap tokens for tokens
* @param factory Uniswap V2-compliant Factory contract
* @param trade Trade details
*/
function _swapTokensForExactTokens(
address factory,
Trade calldata trade
) internal {
uint[] memory amounts = RouteLib.getAmountsIn(factory, trade.amountOut, trade.path);
require(amounts[0] <= trade.amountIn, 'ArchRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
trade.path[0], msg.sender, RouteLib.pairFor(factory, trade.path[0], trade.path[1]), amounts[0]
);
_exactOutputSwap(factory, amounts, trade.path, trade.to);
}
/**
* @notice Internal implementation of exact input Uni V2/Sushi swap
* @param factory Uniswap V2-compliant Factory contract
* @param path Trade path
* @param _to Trade recipient
*/
function _exactInputSwap(
address factory,
address[] memory path,
address _to
) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = RouteLib.sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(RouteLib.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20Extended(input).balanceOf(address(pair)) - reserveInput;
amountOutput = RouteLib.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
/**
* @notice Internal implementation of exact output Uni V2/Sushi swap
* @param factory Uniswap V2-compliant Factory contract
* @param amounts Output amounts
* @param path Trade path
* @param _to Trade recipient
*/
function _exactOutputSwap(
address factory,
uint[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = RouteLib.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? RouteLib.pairFor(factory, output, path[i + 2]) : _to;
IUniswapV2Pair(RouteLib.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
/**
* @notice Convert a token balance into ETH and then tip
* @param factory Factory address
* @param path Path for swap
*/
function _tipWithTokens(
address factory,
address[] memory path
) internal {
_exactInputSwap(factory, path, address(this));
uint256 amountOut = IWETH(WETH).balanceOf(address(this));
IWETH(WETH).withdraw(amountOut);
tip(address(this).balance);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IMulticall.sol';
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/IPayments.sol';
import './interfaces/IWETH.sol';
import './lib/TransferHelper.sol';
import './ArchRouterImmutableState.sol';
abstract contract Payments is IPayments, ArchRouterImmutableState {
receive() external payable {
require(msg.sender == WETH, 'Not WETH');
}
/// @inheritdoc IPayments
function unwrapWETH(uint256 amountMinimum, address recipient) external payable override {
uint256 balanceWETH = withdrawWETH(amountMinimum);
TransferHelper.safeTransferETH(recipient, balanceWETH);
}
/// @inheritdoc IPayments
function unwrapWETHAndTip(uint256 tipAmount, uint256 amountMinimum, address recipient) external payable override {
uint256 balanceWETH = withdrawWETH(amountMinimum);
tip(tipAmount);
if(balanceWETH > tipAmount) {
TransferHelper.safeTransferETH(recipient, balanceWETH - tipAmount);
}
}
/// @inheritdoc IPayments
function tip(uint256 tipAmount) public payable override {
TransferHelper.safeTransferETH(block.coinbase, tipAmount);
}
/// @inheritdoc IPayments
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable override {
uint256 balanceToken = IERC20Extended(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
/// @inheritdoc IPayments
function refundETH() external payable override {
if (address(this).balance > 0) TransferHelper.safeTransferETH(msg.sender, address(this).balance);
}
/// @param amountMinimum Min amount of WETH to withdraw
function withdrawWETH(uint256 amountMinimum) public returns(uint256 balanceWETH){
balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= amountMinimum && balanceWETH > 0, 'Insufficient WETH');
IWETH(WETH).withdraw(balanceWETH);
}
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(
address token,
address payer,
address recipient,
uint256 value
) internal {
if (token == WETH && address(this).balance >= value) {
// pay with WETH
IWETH(WETH).deposit{value: value}(); // wrap only what is needed to pay
IWETH(WETH).transfer(recipient, value);
} else if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/IPaymentsWithFee.sol';
import './interfaces/IWETH.sol';
import './lib/TransferHelper.sol';
import './Payments.sol';
abstract contract PaymentsWithFee is Payments, IPaymentsWithFee {
/// @inheritdoc IPaymentsWithFee
function unwrapWETHWithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceWETH = IWETH(WETH).balanceOf(address(this));
require(balanceWETH >= amountMinimum, 'Insufficient WETH');
if (balanceWETH > 0) {
IWETH(WETH).withdraw(balanceWETH);
uint256 feeAmount = (balanceWETH * feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransferETH(feeRecipient, feeAmount);
TransferHelper.safeTransferETH(recipient, balanceWETH - feeAmount);
}
}
/// @inheritdoc IPaymentsWithFee
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) public payable override {
require(feeBips > 0 && feeBips <= 100);
uint256 balanceToken = IERC20Extended(token).balanceOf(address(this));
require(balanceToken >= amountMinimum, 'Insufficient token');
if (balanceToken > 0) {
uint256 feeAmount = (balanceToken * feeBips) / 10_000;
if (feeAmount > 0) TransferHelper.safeTransfer(token, feeRecipient, feeAmount);
TransferHelper.safeTransfer(token, recipient, balanceToken - feeAmount);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './interfaces/IERC20Extended.sol';
import './interfaces/ISelfPermit.sol';
import './interfaces/IERC20PermitAllowed.sol';
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
/// @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function
/// that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit {
/// @inheritdoc ISelfPermit
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20Extended(token).permit(msg.sender, address(this), value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20Extended(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public payable override {
IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s);
}
/// @inheritdoc ISelfPermit
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable override {
if (IERC20Extended(token).allowance(msg.sender, address(this)) < type(uint256).max)
selfPermitAllowed(token, nonce, expiry, v, r, s);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IArchRouterImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function uniV3Factory() external view returns (address);
/// @return Returns the address of WETH
function WETH() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20Extended {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function version() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;
function receiveWithAuthorization(address from, address to, uint256 value, uint256 validAfter, uint256 validBefore, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external;
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function nonces(address) external view returns (uint);
function getDomainSeparator() external view returns (bytes32);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function DOMAIN_TYPEHASH() external view returns (bytes32);
function VERSION_HASH() external view returns (bytes32);
function PERMIT_TYPEHASH() external view returns (bytes32);
function TRANSFER_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
function RECEIVE_WITH_AUTHORIZATION_TYPEHASH() external view returns (bytes32);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
event AuthorizationUsed(address indexed authorizer, bytes32 indexed nonce);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Interface for permit
/// @notice Interface used by DAI/CHAI for permit
interface IERC20PermitAllowed {
/// @notice Approve the spender to spend some tokens via the holder signature
/// @dev This is the permit interface used by DAI and CHAI
/// @param holder The address of the token holder, the token owner
/// @param spender The address of the token spender
/// @param nonce The holder's nonce, increases at each call to permit
/// @param expiry The timestamp at which the permit is no longer valid
/// @param allowed Boolean that sets approval amount, true for type(uint256).max and false for 0
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPayments {
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users.
/// @param amountMinimum The minimum amount of WETH to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Tips miners using the WETH balance in the contract and then transfers the remainder to recipient
/// @dev The recipientMinimum parameter prevents malicious contracts from stealing the ETH from users
/// @param tipAmount Tip amount
/// @param amountMinimum The minimum amount of WETH to withdraw
/// @param recipient The destination address of the ETH left after tipping
function unwrapWETHAndTip(
uint256 tipAmount,
uint256 amountMinimum,
address recipient
) external payable;
/// @notice Tips miners using the ETH balance in the contract + msg.value
/// @param tipAmount Tip amount
function tip(
uint256 tipAmount
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './IPayments.sol';
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPaymentsWithFee is IPayments {
/// @notice Unwraps the contract's WETH balance and sends it to recipient as ETH, with a percentage between
/// 0 (exclusive), and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH from users.
function unwrapWETHWithFee(
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient, with a percentage between
/// 0 (exclusive) and 1 (inclusive) going to feeRecipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
function sweepTokenWithFee(
address token,
uint256 amountMinimum,
address recipient,
uint256 feeBips,
address feeRecipient
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
/// @title Self Permit
/// @notice Functionality to call permit on any EIP-2612-compliant token for use in the route
interface ISelfPermit {
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermit(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend a given token from `msg.sender`
/// @dev The `owner` is always msg.sender and the `spender` is always address(this).
/// Can be used instead of #selfPermit to prevent calls from failing due to a frontrun of a call to #selfPermit
/// @param token The address of the token spent
/// @param value The amount that can be spent of token
/// @param deadline A timestamp, the current blocktime must be less than or equal to this timestamp
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitIfNecessary(
address token,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowed(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
/// @notice Permits this contract to spend the sender's tokens for permit signatures that have the `allowed` parameter
/// @dev The `owner` is always msg.sender and the `spender` is always address(this)
/// Can be used instead of #selfPermitAllowed to prevent calls from failing due to a frontrun of a call to #selfPermitAllowed.
/// @param token The address of the token spent
/// @param nonce The current nonce of the owner
/// @param expiry The timestamp at which the permit is no longer valid
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function selfPermitAllowedIfNecessary(
address token,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import './IUniswapV3SwapCallback.sol';
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniV3Router is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniswapV2Pair {
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool
{
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function transfer(address recipient, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity ^0.8.0;
library BytesLib {
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, 'slice_overflow');
require(_start + _length >= _start, 'slice_overflow');
require(_bytes.length >= _start + _length, 'slice_outOfBounds');
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_start + 20 >= _start, 'toAddress_overflow');
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_start + 3 >= _start, 'toUint24_overflow');
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import '../interfaces/IUniswapV3Pool.sol';
import './RouteLib.sol';
/// @notice Provides validation for callbacks from Uniswap V3 Pools
library CallbackValidation {
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param tokenA The contract address of either token0 or token1
/// @param tokenB The contract address of the other token
/// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
/// @return pool The V3 pool contract address
function verifyCallback(
address factory,
address tokenA,
address tokenB,
uint24 fee
) internal view returns (IUniswapV3Pool pool) {
return verifyCallback(factory, RouteLib.getPoolKey(tokenA, tokenB, fee));
}
/// @notice Returns the address of a valid Uniswap V3 Pool
/// @param factory The contract address of the Uniswap V3 factory
/// @param poolKey The identifying key of the V3 pool
/// @return pool The V3 pool contract address
function verifyCallback(address factory, RouteLib.PoolKey memory poolKey)
internal
view
returns (IUniswapV3Pool pool)
{
pool = IUniswapV3Pool(RouteLib.computeAddress(factory, poolKey));
require(msg.sender == address(pool));
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import './BytesLib.sol';
/// @title Functions for manipulating path data for multihop swaps
library Path {
using BytesLib for bytes;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev The offset of an encoded pool key
uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE;
/// @dev The minimum length of an encoding that contains 2 or more pools
uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET;
/// @notice Returns true iff the path contains two or more pools
/// @param path The encoded swap path
/// @return True if path contains two or more pools, otherwise false
function hasMultiplePools(bytes memory path) internal pure returns (bool) {
return path.length >= MULTIPLE_POOLS_MIN_LENGTH;
}
/// @notice Decodes the first pool in path
/// @param path The bytes encoded swap path
/// @return tokenA The first token of the given pool
/// @return tokenB The second token of the given pool
/// @return fee The fee level of the pool
function decodeFirstPool(bytes memory path)
internal
pure
returns (
address tokenA,
address tokenB,
uint24 fee
)
{
tokenA = path.toAddress(0);
fee = path.toUint24(ADDR_SIZE);
tokenB = path.toAddress(NEXT_OFFSET);
}
/// @notice Gets the segment corresponding to the first pool in the path
/// @param path The bytes encoded swap path
/// @return The segment containing all data necessary to target the first pool in the path
function getFirstPool(bytes memory path) internal pure returns (bytes memory) {
return path.slice(0, POP_OFFSET);
}
/// @notice Skips a token + fee element from the buffer and returns the remainder
/// @param path The swap path
/// @return The remaining token + fee elements in the path
function skipToken(bytes memory path) internal pure returns (bytes memory) {
return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '../interfaces/IUniswapV2Pair.sol';
library RouteLib {
address internal constant _SUSHI_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
bytes32 internal constant _SUSHI_ROUTER_INIT_HASH = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303;
bytes32 internal constant _UNI_V2_ROUTER_INIT_HASH = 0x96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f;
bytes32 internal constant _UNI_V3_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
/// @notice The identifying key of the pool
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
/// @notice Returns PoolKey: the ordered tokens with the matched fee levels
/// @param tokenA The first token of a pool, unsorted
/// @param tokenB The second token of a pool, unsorted
/// @param fee The fee level of the pool
/// @return Poolkey The pool details with ordered token0 and token1 assignments
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
}
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'RouteLib: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'RouteLib: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
bytes32 initHash = factory == _SUSHI_FACTORY ? _SUSHI_ROUTER_INIT_HASH : _UNI_V2_ROUTER_INIT_HASH;
pair = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
initHash // init code hash
)
)
)
)
);
}
/// @notice Deterministically computes the pool address given the factory and PoolKey
/// @param factory The Uniswap V3 factory contract address
/// @param key The PoolKey
/// @return pool The contract address of the V3 pool
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
_UNI_V3_INIT_CODE_HASH
)
)
)
)
);
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'RouteLib: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
amountB = amountA * (reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'RouteLib: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = reserveIn * 1000 + amountInWithFee;
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'RouteLib: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'RouteLib: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn * amountOut * 1000;
uint denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'RouteLib: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'RouteLib: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y < 2**255);
z = int256(y);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
| @inheritdoc IUniV3Router the outputs of prior swaps become the inputs to subsequent ones decide whether to continue or terminate | function exactInput(ExactInputParams memory params)
public
payable
override
returns (uint256 amountOut)
{
while (true) {
bool hasMultiplePools = params.path.hasMultiplePools();
params.amountIn = _exactInputInternal(
params.amountIn,
0,
SwapCallbackData({
payer: payer
})
);
if (hasMultiplePools) {
params.path = params.path.skipToken();
amountOut = params.amountIn;
break;
}
}
require(amountOut >= params.amountOutMinimum, 'Too little received');
}
| 11,683,076 | [
1,
36,
10093,
467,
984,
77,
58,
23,
8259,
326,
6729,
434,
6432,
1352,
6679,
12561,
326,
4540,
358,
10815,
5945,
16288,
2856,
358,
1324,
578,
10850,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5565,
1210,
12,
14332,
1210,
1370,
3778,
859,
13,
203,
3639,
1071,
203,
3639,
8843,
429,
203,
3639,
3849,
203,
3639,
1135,
261,
11890,
5034,
3844,
1182,
13,
203,
565,
288,
203,
203,
3639,
1323,
261,
3767,
13,
288,
203,
5411,
1426,
711,
8438,
16639,
273,
859,
18,
803,
18,
5332,
8438,
16639,
5621,
203,
203,
5411,
859,
18,
8949,
382,
273,
389,
17165,
1210,
3061,
12,
203,
7734,
859,
18,
8949,
382,
16,
203,
7734,
374,
16,
203,
7734,
12738,
2428,
751,
12590,
203,
10792,
293,
1773,
30,
293,
1773,
203,
7734,
289,
13,
203,
5411,
11272,
203,
203,
5411,
309,
261,
5332,
8438,
16639,
13,
288,
203,
7734,
859,
18,
803,
273,
859,
18,
803,
18,
7457,
1345,
5621,
203,
7734,
3844,
1182,
273,
859,
18,
8949,
382,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
12,
8949,
1182,
1545,
859,
18,
8949,
1182,
13042,
16,
296,
10703,
12720,
5079,
8284,
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
] |
./full_match/5/0xCaC257E8794C1884C9BB5707C651b975f844CC12/sources/project_/contracts/ProxyFactory.sol | copy init code into memory and immutable ExchangeDeposit address onto stack Get the position of the start of init code grab the first 32 bytes shift the address bytes 8 bits left bitwise OR them and add the address into the init code memory create the contract revert if failed | function deployNewInstances(uint256 instanceAmount) external returns (address[] memory dsts) {
bytes memory initCodeMem = INIT_CODE;
address payable addrStack = mainAddress;
address dst = address(0);
dsts = new address[](instanceAmount);
for(uint256 i=saltCnt; i<saltCnt + instanceAmount; i++) {
assembly {
let pos := add(initCodeMem, 0x20)
let first32 := mload(pos)
let addrBytesShifted := shl(8, addrStack)
mstore(pos, or(first32, addrBytesShifted))
dst := create2(
)
if eq(dst, 0) {
revert(0, 0)
}
}
dsts[i-saltCnt] = dst;
saltCnt = saltCnt + instanceAmount;
}
return dsts;
}
| 7,082,846 | [
1,
3530,
1208,
981,
1368,
3778,
471,
11732,
18903,
758,
1724,
1758,
10170,
2110,
968,
326,
1754,
434,
326,
787,
434,
1208,
981,
11086,
326,
1122,
3847,
1731,
4654,
326,
1758,
1731,
1725,
4125,
2002,
25337,
4869,
2182,
471,
527,
326,
1758,
1368,
326,
1208,
981,
3778,
752,
326,
6835,
15226,
309,
2535,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7286,
1908,
5361,
12,
11890,
5034,
791,
6275,
13,
3903,
1135,
261,
2867,
8526,
3778,
3046,
87,
13,
288,
203,
3639,
1731,
3778,
1208,
1085,
3545,
273,
12584,
67,
5572,
31,
203,
3639,
1758,
8843,
429,
3091,
2624,
273,
2774,
1887,
31,
203,
3639,
1758,
3046,
273,
1758,
12,
20,
1769,
203,
3639,
3046,
87,
225,
273,
394,
1758,
8526,
12,
1336,
6275,
1769,
203,
203,
3639,
364,
12,
11890,
5034,
277,
33,
5759,
11750,
31,
277,
32,
5759,
11750,
397,
791,
6275,
31,
277,
27245,
288,
203,
5411,
19931,
288,
203,
7734,
2231,
949,
519,
527,
12,
2738,
1085,
3545,
16,
374,
92,
3462,
13,
203,
7734,
2231,
1122,
1578,
519,
312,
945,
12,
917,
13,
203,
7734,
2231,
3091,
2160,
10544,
329,
519,
699,
80,
12,
28,
16,
3091,
2624,
13,
203,
7734,
312,
2233,
12,
917,
16,
578,
12,
3645,
1578,
16,
3091,
2160,
10544,
329,
3719,
203,
7734,
3046,
519,
752,
22,
12,
203,
7734,
262,
203,
7734,
309,
7555,
12,
11057,
16,
374,
13,
288,
203,
10792,
15226,
12,
20,
16,
374,
13,
203,
7734,
289,
203,
5411,
289,
203,
5411,
3046,
87,
63,
77,
17,
5759,
11750,
65,
273,
3046,
31,
203,
5411,
4286,
11750,
273,
4286,
11750,
397,
791,
6275,
31,
203,
3639,
289,
203,
3639,
327,
3046,
87,
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
] |
./partial_match/4/0xFFCAaE2a77254B4cd72356B27377408ab31155b4/sources/CallMarket.sol | we need to compute the parent of this last element which is p = (k-1)/2
| uint256 p = (k-1)/2; | 8,538,457 | [
1,
1814,
1608,
358,
3671,
326,
982,
434,
333,
1142,
930,
1492,
353,
293,
273,
261,
79,
17,
21,
13176,
22,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
2254,
5034,
293,
273,
261,
79,
17,
21,
13176,
22,
31,
11794,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "hardhat/console.sol";
import "../ubeswap-farming/interfaces/IStakingRewards.sol";
import "./common/RevoUniswapStakingTokenStrategy.sol";
import "../openzeppelin-solidity/contracts/SafeERC20.sol";
/**
* RevoUbeswapSingleRewardFarmBot is a farmbot:
* * that runs on top of an IStakingRewards farm
* * whose stakingToken is an IUniswapV2Pair ("LP")
* * that acquires LP constintuent tokens through swaps on an IUniswapV2Router02
* * that mints LP from constituent tokens through an IUniswapV2Router02
*
* This farmbot is suitable for use on top of Ubeswap farms that have a single reward token.
**/
contract RevoUbeswapSingleRewardFarmBot is RevoUniswapStakingTokenStrategy {
using SafeERC20 for IERC20;
IStakingRewards public stakingRewards;
constructor(
address _owner,
address _reserveAddress,
address _stakingRewards,
address _stakingToken,
address _revoFees,
address[] memory _rewardsTokens,
address _swapRouter,
address _liquidityRouter,
string memory _symbol
)
RevoUniswapStakingTokenStrategy(
_owner,
_reserveAddress,
_stakingToken,
_revoFees,
_rewardsTokens,
_swapRouter,
_liquidityRouter,
_symbol
)
{
require(
_rewardsTokens.length == 1,
"Must specify exactly one rewards token"
);
stakingRewards = IStakingRewards(_stakingRewards);
}
function _deposit(uint256 _lpAmount) internal override whenNotPaused {
require(_lpAmount > 0, "Cannot invest in farm because lpAmount is 0");
stakingToken.safeIncreaseAllowance(address(stakingRewards), _lpAmount);
stakingRewards.stake(_lpAmount);
}
function _withdraw(uint256 _lpAmount) internal override {
stakingRewards.withdraw(_lpAmount);
}
function _claimRewards() internal override whenNotPaused {
stakingRewards.getReward();
}
}
| * RevoUbeswapSingleRewardFarmBot is a farmbot: that runs on top of an IStakingRewards farm whose stakingToken is an IUniswapV2Pair ("LP") that acquires LP constintuent tokens through swaps on an IUniswapV2Router02 that mints LP from constituent tokens through an IUniswapV2Router02 This farmbot is suitable for use on top of Ubeswap farms that have a single reward token./ | contract RevoUbeswapSingleRewardFarmBot is RevoUniswapStakingTokenStrategy {
using SafeERC20 for IERC20;
IStakingRewards public stakingRewards;
constructor(
address _owner,
address _reserveAddress,
address _stakingRewards,
address _stakingToken,
address _revoFees,
address[] memory _rewardsTokens,
address _swapRouter,
address _liquidityRouter,
string memory _symbol
)
RevoUniswapStakingTokenStrategy(
_owner,
_reserveAddress,
_stakingToken,
_revoFees,
_rewardsTokens,
_swapRouter,
_liquidityRouter,
_symbol
)
pragma solidity 0.8.4;
{
require(
_rewardsTokens.length == 1,
"Must specify exactly one rewards token"
);
stakingRewards = IStakingRewards(_stakingRewards);
}
function _deposit(uint256 _lpAmount) internal override whenNotPaused {
require(_lpAmount > 0, "Cannot invest in farm because lpAmount is 0");
stakingToken.safeIncreaseAllowance(address(stakingRewards), _lpAmount);
stakingRewards.stake(_lpAmount);
}
function _withdraw(uint256 _lpAmount) internal override {
stakingRewards.withdraw(_lpAmount);
}
function _claimRewards() internal override whenNotPaused {
stakingRewards.getReward();
}
}
| 5,472,627 | [
1,
10070,
83,
57,
70,
281,
91,
438,
5281,
17631,
1060,
42,
4610,
6522,
353,
279,
10247,
1627,
352,
30,
565,
716,
7597,
603,
1760,
434,
392,
467,
510,
6159,
17631,
14727,
284,
4610,
565,
8272,
384,
6159,
1345,
353,
392,
467,
984,
291,
91,
438,
58,
22,
4154,
7566,
14461,
7923,
565,
716,
1721,
4138,
511,
52,
1866,
474,
10744,
2430,
3059,
1352,
6679,
603,
392,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
565,
716,
312,
28142,
511,
52,
628,
29152,
10744,
2430,
3059,
392,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1220,
10247,
1627,
352,
353,
10631,
364,
999,
603,
1760,
434,
587,
70,
281,
91,
438,
10247,
959,
716,
1240,
279,
2202,
19890,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
868,
12307,
57,
70,
281,
91,
438,
5281,
17631,
1060,
42,
4610,
6522,
353,
868,
12307,
984,
291,
91,
438,
510,
6159,
1345,
4525,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
467,
510,
6159,
17631,
14727,
1071,
384,
6159,
17631,
14727,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
1758,
389,
455,
6527,
1887,
16,
203,
3639,
1758,
389,
334,
6159,
17631,
14727,
16,
203,
3639,
1758,
389,
334,
6159,
1345,
16,
203,
3639,
1758,
389,
9083,
83,
2954,
281,
16,
203,
3639,
1758,
8526,
3778,
389,
266,
6397,
5157,
16,
203,
3639,
1758,
389,
22270,
8259,
16,
203,
3639,
1758,
389,
549,
372,
24237,
8259,
16,
203,
3639,
533,
3778,
389,
7175,
203,
565,
262,
203,
3639,
868,
12307,
984,
291,
91,
438,
510,
6159,
1345,
4525,
12,
203,
5411,
389,
8443,
16,
203,
5411,
389,
455,
6527,
1887,
16,
203,
5411,
389,
334,
6159,
1345,
16,
203,
5411,
389,
9083,
83,
2954,
281,
16,
203,
5411,
389,
266,
6397,
5157,
16,
203,
5411,
389,
22270,
8259,
16,
203,
5411,
389,
549,
372,
24237,
8259,
16,
203,
5411,
389,
7175,
203,
3639,
262,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
24,
31,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
389,
266,
6397,
5157,
18,
2469,
422,
404,
16,
203,
5411,
315,
10136,
4800,
8950,
1245,
283,
6397,
1147,
6,
203,
3639,
11272,
203,
3639,
384,
6159,
17631,
14727,
273,
467,
510,
6159,
2
] |
./partial_match/1/0xfa4B1e50709e8890f23866f16da26B8a4780e464/sources/veSaddleVault.sol | Set governance for this token | constructor() {
governance = msg.sender;
DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this)));
}
| 4,447,815 | [
1,
694,
314,
1643,
82,
1359,
364,
333,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
3639,
314,
1643,
82,
1359,
273,
1234,
18,
15330,
31,
203,
3639,
27025,
4550,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
18192,
67,
2399,
15920,
16,
417,
24410,
581,
5034,
12,
3890,
12,
529,
13,
3631,
389,
588,
3893,
548,
9334,
1758,
12,
2211,
3719,
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
] |
./full_match/137/0xCbfb6507632A5d73667dEe6966042B3a430e9663/sources/contracts/LimitOrderManager/LimitOrderManager.sol | is 0 if not explicitly set
| uint256 index = orderIndexes[_orderId]; | 4,697,903 | [
1,
291,
374,
309,
486,
8122,
444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
770,
273,
1353,
8639,
63,
67,
1019,
548,
15533,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol | * @inheritdoc IAccessControlDefaultAdminRules/ | function defaultAdmin() public view virtual returns (address) {
return _currentDefaultAdmin;
}
| 8,082,616 | [
1,
36,
10093,
467,
16541,
1868,
4446,
4478,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
805,
4446,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
2972,
1868,
4446,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// contracts/WrappedStrax.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/token/ERC20/ERC20.sol";
contract WrappedStraxToken is ERC20, Ownable {
mapping (address => string) public withdrawalAddresses;
constructor(uint256 initialSupply) public ERC20("WrappedStrax", "WSTRAX") {
_mint(msg.sender, initialSupply);
}
/**
* @dev Creates `amount` new tokens and assigns them to `account`.
*
* See {ERC20-_mint}.
*/
function mint(address account, uint256 amount) public onlyOwner {
_mint(account, amount);
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount, string memory straxAddress) public {
_burn(_msgSender(), amount);
// When the tokens are burnt we need to know where to credit the equivalent value on the Stratis chain.
// Currently it is only possible to assign a single address here, so if multiple recipients are required
// the burner will have to wait until each burn is processed before proceeding with the next.
withdrawalAddresses[msg.sender] = straxAddress;
}
/**
* @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, string memory straxAddress) public {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
// When the tokens are burnt we need to know where to credit the equivalent value on the Stratis chain.
// Currently it is only possible to assign a single address here, so if multiple recipients are required
// the burner will have to wait until each burn is processed before proceeding with the next.
withdrawalAddresses[msg.sender] = straxAddress;
}
}
| * @dev Destroys `amount` tokens from the caller. See {ERC20-_burn}./ When the tokens are burnt we need to know where to credit the equivalent value on the Stratis chain. Currently it is only possible to assign a single address here, so if multiple recipients are required the burner will have to wait until each burn is processed before proceeding with the next. | function burn(uint256 amount, string memory straxAddress) public {
_burn(_msgSender(), amount);
withdrawalAddresses[msg.sender] = straxAddress;
}
| 1,036,883 | [
1,
9378,
28599,
1375,
8949,
68,
2430,
628,
326,
4894,
18,
2164,
288,
654,
39,
3462,
17,
67,
70,
321,
5496,
19,
5203,
326,
2430,
854,
18305,
88,
732,
1608,
358,
5055,
1625,
358,
12896,
326,
7680,
460,
603,
326,
3978,
270,
291,
2687,
18,
15212,
518,
353,
1338,
3323,
358,
2683,
279,
2202,
1758,
2674,
16,
1427,
309,
3229,
12045,
854,
1931,
326,
18305,
264,
903,
1240,
358,
2529,
3180,
1517,
18305,
353,
5204,
1865,
11247,
310,
598,
326,
1024,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
18305,
12,
11890,
5034,
3844,
16,
533,
3778,
609,
651,
1887,
13,
1071,
288,
203,
3639,
389,
70,
321,
24899,
3576,
12021,
9334,
3844,
1769,
203,
540,
203,
3639,
598,
9446,
287,
7148,
63,
3576,
18,
15330,
65,
273,
609,
651,
1887,
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
] |
//Address: 0xa6714a2e5f0b1bdb97b895b0913b4fcd3a775e4d
//Contract name: PromotionCoin
//Balance: 0 Ether
//Verification Date: 2/5/2018
//Transacion Count: 30887
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract DateTime {
/*
* Date and Time utilities for ethereum contracts
*
*/
struct _DateTime {
uint16 year;
uint8 month;
uint8 day;
uint8 hour;
uint8 minute;
uint8 second;
uint8 weekday;
}
uint constant DAY_IN_SECONDS = 86400;
uint constant YEAR_IN_SECONDS = 31536000;
uint constant LEAP_YEAR_IN_SECONDS = 31622400;
uint constant HOUR_IN_SECONDS = 3600;
uint constant MINUTE_IN_SECONDS = 60;
uint16 constant ORIGIN_YEAR = 1970;
function isLeapYear(uint16 year) public pure returns (bool) {
if (year % 4 != 0) {
return false;
}
if (year % 100 != 0) {
return true;
}
if (year % 400 != 0) {
return false;
}
return true;
}
function leapYearsBefore(uint year) public pure returns (uint) {
year -= 1;
return year / 4 - year / 100 + year / 400;
}
function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
return 31;
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) {
uint secondsAccountedFor = 0;
uint buf;
uint8 i;
// Year
dt.year = getYear(timestamp);
buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf;
secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf);
// Month
uint secondsInMonth;
for (i = 1; i <= 12; i++) {
secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year);
if (secondsInMonth + secondsAccountedFor > timestamp) {
dt.month = i;
break;
}
secondsAccountedFor += secondsInMonth;
}
// Day
for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) {
if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) {
dt.day = i;
break;
}
secondsAccountedFor += DAY_IN_SECONDS;
}
// Hour
dt.hour = getHour(timestamp);
// Minute
dt.minute = getMinute(timestamp);
// Second
dt.second = getSecond(timestamp);
// Day of week.
dt.weekday = getWeekday(timestamp);
}
function getYear(uint timestamp) public pure returns (uint16) {
uint secondsAccountedFor = 0;
uint16 year;
uint numLeapYears;
// Year
year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS);
numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR);
secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears;
secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears);
while (secondsAccountedFor > timestamp) {
if (isLeapYear(uint16(year - 1))) {
secondsAccountedFor -= LEAP_YEAR_IN_SECONDS;
} else {
secondsAccountedFor -= YEAR_IN_SECONDS;
}
year -= 1;
}
return year;
}
function getMonth(uint timestamp) public pure returns (uint8) {
return parseTimestamp(timestamp).month;
}
function getDay(uint timestamp) public pure returns (uint8) {
return parseTimestamp(timestamp).day;
}
function getHour(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60 / 60) % 24);
}
function getMinute(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / 60) % 60);
}
function getSecond(uint timestamp) public pure returns (uint8) {
return uint8(timestamp % 60);
}
function getWeekday(uint timestamp) public pure returns (uint8) {
return uint8((timestamp / DAY_IN_SECONDS + 4) % 7);
}
function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, 0, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, 0, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) {
return toTimestamp(year, month, day, hour, minute, 0);
}
function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) {
uint16 i;
// Year
for (i = ORIGIN_YEAR; i < year; i++) {
if (isLeapYear(i)) {
timestamp += LEAP_YEAR_IN_SECONDS;
} else {
timestamp += YEAR_IN_SECONDS;
}
}
// Month
uint8[12] memory monthDayCounts;
monthDayCounts[0] = 31;
if (isLeapYear(year)) {
monthDayCounts[1] = 29;
} else {
monthDayCounts[1] = 28;
}
monthDayCounts[2] = 31;
monthDayCounts[3] = 30;
monthDayCounts[4] = 31;
monthDayCounts[5] = 30;
monthDayCounts[6] = 31;
monthDayCounts[7] = 31;
monthDayCounts[8] = 30;
monthDayCounts[9] = 31;
monthDayCounts[10] = 30;
monthDayCounts[11] = 31;
for (i = 1; i < month; i++) {
timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1];
}
// Day
timestamp += DAY_IN_SECONDS * (day - 1);
// Hour
timestamp += HOUR_IN_SECONDS * (hour);
// Minute
timestamp += MINUTE_IN_SECONDS * (minute);
// Second
timestamp += second;
return timestamp;
}
}
/**
* @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 Authorizable
* @dev Allows to authorize access to certain function calls
*
* ABI
* [{"constant":true,"inputs":[{"name":"authorizerIndex","type":"uint256"}],"name":"getAuthorizer","outputs":[{"name":"","type":"address"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"_addr","type":"address"}],"name":"addAuthorized","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"_addr","type":"address"}],"name":"isAuthorized","outputs":[{"name":"","type":"bool"}],"payable":false,"type":"function"},{"inputs":[],"payable":false,"type":"constructor"}]
*/
contract Authorizable {
address[] authorizers;
mapping(address => uint) authorizerIndex;
/**
* @dev Throws if called by any account tat is not authorized.
*/
modifier onlyAuthorized {
require(isAuthorized(msg.sender));
_;
}
/**
* @dev Contructor that authorizes the msg.sender.
*/
function Authorizable() public {
authorizers.length = 2;
authorizers[1] = msg.sender;
authorizerIndex[msg.sender] = 1;
}
/**
* @dev Function to get a specific authorizer
* @param _authorizerIndex index of the authorizer to be retrieved.
* @return The address of the authorizer.
*/
function getAuthorizer(uint _authorizerIndex) external view returns(address) {
return address(authorizers[_authorizerIndex + 1]);
}
/**
* @dev Function to check if an address is authorized
* @param _addr the address to check if it is authorized.
* @return boolean flag if address is authorized.
*/
function isAuthorized(address _addr) public view returns(bool) {
return authorizerIndex[_addr] > 0;
}
/**
* @dev Function to add a new authorizer
* @param _addr the address to add as a new authorizer.
*/
function addAuthorized(address _addr) external onlyAuthorized {
authorizerIndex[_addr] = authorizers.length;
authorizers.length++;
authorizers[authorizers.length - 1] = _addr;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @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];
}
/**
* 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
*/
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;
}
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) public onlyOwner canMint 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() public onlyOwner canMint returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title PromotionCoin
* @dev The main PC token contract
*/
contract PromotionCoin is MintableToken {
string public name = "PromotionCoin";
string public symbol = "PC";
uint public decimals = 5;
/**
* @dev Allows anyone to transfer
* @param _to the recipient address of the tokens.
* @param _value number of tokens to be transfered.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
super.transfer(_to, _value);
}
/**
* @dev Allows anyone to transfer
* @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 uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
super.transferFrom(_from, _to, _value);
}
}
/**
* @title PromotionCoinDistribution
* @dev The main PC token sale contract
*
* ABI
*/
contract PromotionCoinDistribution is Ownable, Authorizable {
using SafeMath for uint;
event AuthorizedCreateToPrivate(address recipient, uint pay_amount);
event Mined(address recipient, uint pay_amount);
event CreateTokenToTeam(address recipient, uint pay_amount);
event CreateTokenToMarket(address recipient, uint pay_amount);
event CreateTokenToOperation(address recipient, uint pay_amount);
event CreateTokenToTax(address recipient, uint pay_amount);
event PromotionCoinMintFinished();
PromotionCoin public token = new PromotionCoin();
DateTime internal dateTime = new DateTime();
uint public DICIMALS = 5;
uint totalToken = 21000000000 * (10 ** DICIMALS); //210亿
uint public privateTokenCap = 5000000000 * (10 ** DICIMALS); //私募发行50亿
uint public marketToken2018 = 0.50 * 1500000000 * (10 ** DICIMALS); //全球推广15亿,第一年 50%
uint public marketToken2019 = 0.25 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第二年 25%
uint public marketToken2020 = 0.15 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第三年 15%
uint public marketToken2021 = 0.10 * 1500000000 * (10 ** DICIMALS); //全球推广15亿, 第四年 10%
uint public operationToken = 2000000000 * (10 ** DICIMALS); //社区运营20亿
uint public minedTokenCap = 11000000000 * (10 ** DICIMALS); //挖矿110亿
uint public teamToken2018 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2018年发放5亿
uint public teamToken2019 = 500000000 * (10 ** DICIMALS); //团队预留10亿(10%),2019年发放5亿
uint public taxToken = 500000000 * (10 ** DICIMALS); //税务及法务年发放5亿
uint public privateToken = 0; //私募已发行数量
address public teamAddress;
address public operationAddress;
address public marketAddress;
address public taxAddress;
bool public team2018TokenCreated = false;
bool public team2019TokenCreated = false;
bool public operationTokenCreated = false;
bool public market2018TokenCreated = false;
bool public market2019TokenCreated = false;
bool public market2020TokenCreated = false;
bool public market2021TokenCreated = false;
bool public taxTokenCreated = false;
//year => token
mapping(uint16 => uint) public minedToken; //游戏挖矿已发行数量
uint public firstYearMinedTokenCap = 5500000000 * (10 ** DICIMALS); //2018年55亿(110亿*0.5),以后逐年减半
uint public minedTokenStartTime = 1514736000; //new Date("Jan 01 2018 00:00:00 GMT+8").getTime() / 1000;
function isContract(address _addr) internal view returns(bool) {
uint size;
if (_addr == 0)
return false;
assembly {
size := extcodesize(_addr)
}
return size > 0;
}
//2018年55亿(110亿*0.5),以后逐年减半,到2028年发放剩余的全部
function getCurrentYearMinedTokenCap(uint _currentYear) public view returns(uint) {
require(_currentYear <= 2028);
if (_currentYear < 2028) {
uint divTimes = 2 ** (_currentYear - 2018);
uint currentYearMinedTokenCap = firstYearMinedTokenCap.div(divTimes).div(10 ** DICIMALS).mul(10 ** DICIMALS);
return currentYearMinedTokenCap;
} else if (_currentYear == 2028) {
return 10742188 * (10 ** DICIMALS);
} else {
revert();
}
}
function getCurrentYearRemainToken(uint16 _currentYear) public view returns(uint) {
uint currentYearMinedTokenCap = getCurrentYearMinedTokenCap(_currentYear);
if (minedToken[_currentYear] == 0) {
return currentYearMinedTokenCap;
} else {
return currentYearMinedTokenCap.sub(minedToken[_currentYear]);
}
}
function setTeamAddress(address _address) public onlyAuthorized {
teamAddress = _address;
}
function setMarketAddress(address _address) public onlyAuthorized {
marketAddress = _address;
}
function setOperationAddress(address _address) public onlyAuthorized {
operationAddress = _address;
}
function setTaxAddress(address _address) public onlyAuthorized {
taxAddress = _address;
}
function createTokenToMarket2018() public onlyAuthorized {
require(marketAddress != address(0));
require(market2018TokenCreated == false);
market2018TokenCreated = true;
token.mint(marketAddress, marketToken2018);
CreateTokenToMarket(marketAddress, marketToken2018);
}
function createTokenToMarket2019() public onlyAuthorized {
require(marketAddress != address(0));
require(market2018TokenCreated == false);
market2019TokenCreated = true;
token.mint(marketAddress, marketToken2019);
CreateTokenToMarket(marketAddress, marketToken2019);
}
function createTokenToMarket2020() public onlyAuthorized {
require(marketAddress != address(0));
require(market2020TokenCreated == false);
market2020TokenCreated = true;
token.mint(marketAddress, marketToken2020);
CreateTokenToMarket(marketAddress, marketToken2020);
}
function createTokenToMarket2021() public onlyAuthorized {
require(marketAddress != address(0));
require(market2021TokenCreated == false);
market2021TokenCreated = true;
token.mint(marketAddress, marketToken2021);
CreateTokenToMarket(marketAddress, marketToken2021);
}
function createTokenToOperation() public onlyAuthorized {
require(operationAddress != address(0));
require(operationTokenCreated == false);
operationTokenCreated = true;
token.mint(operationAddress, operationToken);
CreateTokenToOperation(operationAddress, operationToken);
}
function createTokenToTax() public onlyAuthorized {
require(taxAddress != address(0));
require(taxTokenCreated == false);
taxTokenCreated = true;
token.mint(taxAddress, taxToken);
CreateTokenToOperation(taxAddress, taxToken);
}
function _createTokenToTeam(uint16 _currentYear) internal {
if (_currentYear == 2018) {
require(team2018TokenCreated == false);
team2018TokenCreated = true;
token.mint(teamAddress, teamToken2018);
CreateTokenToTeam(teamAddress, teamToken2018);
} else if (_currentYear == 2019) {
require(team2019TokenCreated == false);
team2019TokenCreated = true;
token.mint(teamAddress, teamToken2019);
CreateTokenToTeam(teamAddress, teamToken2019);
} else {
revert();
}
}
function createTokenToTeam() public onlyAuthorized {
require(teamAddress != address(0));
uint16 currentYear = dateTime.getYear(now);
require(currentYear == 2018 || currentYear == 2019);
_createTokenToTeam(currentYear);
}
function mined(address recipient, uint _tokens) public onlyAuthorized {
require(now > minedTokenStartTime);
uint16 currentYear = dateTime.getYear(now);
uint currentYearRemainTokens = getCurrentYearRemainToken(currentYear);
require(_tokens <= currentYearRemainTokens);
minedToken[currentYear] += _tokens;
token.mint(recipient, _tokens);
Mined(recipient, _tokens);
}
function authorizedCreateTokensToPrivate(address recipient, uint _tokens) public onlyAuthorized {
require(privateToken + _tokens <= privateTokenCap);
privateToken += _tokens;
token.mint(recipient, _tokens);
AuthorizedCreateToPrivate(recipient, _tokens);
}
function finishMinting() public onlyOwner {
token.finishMinting();
token.transferOwnership(owner);
PromotionCoinMintFinished();
}
//不允许直接转账以太币购买
function () external {
revert();
}
}
| new Date("Jan 01 2018 00:00:00 GMT+8").getTime() / 1000;
| uint public minedTokenStartTime = 1514736000; | 13,125,861 | [
1,
2704,
2167,
2932,
46,
304,
8743,
14863,
9631,
30,
713,
30,
713,
21706,
15,
28,
20387,
588,
950,
1435,
342,
4336,
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
] | [
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,
2254,
1071,
1131,
329,
1345,
13649,
273,
4711,
29488,
5718,
3784,
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
] |
pragma solidity 0.6.12;
// SPDX-License-Identifier: MIT
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface INBUNIERC20 {
/**
* @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);
event Log(string log);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
interface IFeeApprover {
function check(
address sender,
address recipient,
uint256 amount
) external returns (bool);
function setFeeMultiplier(uint _feeMultiplier) external;
function feePercentX100() external view returns (uint);
function setTokenUniswapPair(address _tokenUniswapPair) external;
function setdfcoreTokenAddress(address _dfcoreTokenAddress) external;
function sync() external;
function calculateAmountsAfterFee(
address sender,
address recipient,
uint256 amount
) external returns (uint256 transferToAmount, uint256 transferToFeeBearerAmount);
function setPaused() external;
}
interface IdfcoreVault {
function addPendingRewards(uint _amount) external;
}
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 logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", 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));
}
}
/**
* @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);
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function migrator() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
function setMigrator(address) external;
}
interface 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 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;
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) 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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract NBUNIERC20 is Context, INBUNIERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
event LiquidityAddition(address indexed dst, uint value);
event LPTokenClaimed(address dst, uint value);
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 public constant initialSupply = 5000e18; // 5k
uint256 public contractStartTimestamp;
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
function initialSetup() internal {
_name = "DFCore.finance";
_symbol = "DFCORE";
_decimals = 18;
_mint(address(this), initialSupply);
contractStartTimestamp = block.timestamp;
createUniswapPairMainnet(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f);
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
// function balanceOf(address account) public override returns (uint256) {
// return _balances[account];
// }
function balanceOf(address _owner) public override view returns (uint256) {
return _balances[_owner];
}
IUniswapV2Router02 public uniswapRouterV2;
IUniswapV2Factory public uniswapFactory;
address public tokenUniswapPair;
function createUniswapPairMainnet(address router, address factory) onlyOwner public returns (address) {
uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // For testing
uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing
require(tokenUniswapPair == address(0), "Token: pool already created");
tokenUniswapPair = uniswapFactory.createPair(
address(uniswapRouterV2.WETH()),
address(this)
);
return tokenUniswapPair;
}
//// Liquidity generation logic
/// Steps - All tokens tat will ever exist go to this contract
/// This contract accepts ETH as payable
/// ETH is mapped to people
/// When liquidity generationevent is over veryone can call
/// the mint LP function
// which will put all the ETH and tokens inside the uniswap contract
/// without any involvement
/// This LP will go into this contract
/// And will be able to proportionally be withdrawn baed on ETH put in
/// A emergency drain function allows the contract owner to drain all ETH and tokens from this contract
/// After the liquidity generation event happened. In case something goes wrong, to send ETH back
string public liquidityGenerationParticipationAgreement = "I agree that the developers and affiliated parties of the dfcore team are not responsible for your funds";
function getSecondsLeftInLiquidityGenerationEvent() public view returns (uint256) {
require(liquidityGenerationOngoing(), "Event over");
console.log("3 days since start is", contractStartTimestamp.add(3 days), "Time now is", block.timestamp);
return contractStartTimestamp.add(3 days).sub(block.timestamp);
}
function liquidityGenerationOngoing() public view returns (bool) {
console.log("3 days since start is", contractStartTimestamp.add(3 days), "Time now is", block.timestamp);
console.log("liquidity generation ongoing", contractStartTimestamp.add(3 days) < block.timestamp);
return contractStartTimestamp.add(3 days) > block.timestamp;
}
// Emergency drain in case of a bug
// Adds all funds to owner to refund people
// Designed to be as simple as possible
function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner {
require(contractStartTimestamp.add(4 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens
(bool success, ) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer failed.");
_balances[msg.sender] = _balances[address(this)];
_balances[address(this)] = 0;
}
uint256 public totalLPTokensMinted;
uint256 public totalETHContributed;
uint256 public LPperETHUnit;
bool public LPGenerationCompleted;
// Sends all avaibile balances and mints LP tokens
// Possible ways this could break addressed
// 1) Multiple calls and resetting amounts - addressed with boolean
// 2) Failed WETH wrapping/unwrapping addressed with checks
// 3) Failure to create LP tokens, addressed with checks
// 4) Unacceptable division errors . Addressed with multiplications by 1e18
// 5) Pair not set - impossible since its set in constructor
function addLiquidityToUniswapdfcorexWETHPair() public onlyOwner {
require(liquidityGenerationOngoing() == false, "Liquidity generation onging");
require(LPGenerationCompleted == false, "Liquidity generation already finished");
totalETHContributed = address(this).balance;
IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);
console.log("Balance of this", totalETHContributed / 1e18);
//Wrap eth
address WETH = uniswapRouterV2.WETH();
IWETH(WETH).deposit{value : totalETHContributed}();
require(address(this).balance == 0 , "Transfer Failed");
IWETH(WETH).transfer(address(pair),totalETHContributed);
emit Transfer(address(this), address(pair), _balances[address(this)]);
_balances[address(pair)] = _balances[address(this)];
_balances[address(this)] = 0;
pair.mint(address(this));
totalLPTokensMinted = pair.balanceOf(address(this));
console.log("Total tokens minted",totalLPTokensMinted);
require(totalLPTokensMinted != 0 , "LP creation failed");
LPperETHUnit = totalLPTokensMinted.mul(1e18).div(totalETHContributed); // 1e18x for change
console.log("Total per LP token", LPperETHUnit);
require(LPperETHUnit != 0 , "LP creation failed");
LPGenerationCompleted = true;
}
mapping (address => uint) public ethContributed;
// Possible ways this could break addressed
// 1) No ageement to terms - added require
// 2) Adding liquidity after generaion is over - added require
// 3) Overflow from uint - impossible there isnt that much ETH aviable
// 4) Depositing 0 - not an issue it will just add 0 to tally
function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable {
require(liquidityGenerationOngoing(), "Liquidity Generation Event over");
require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided");
ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here
totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE. This resets with definietly correct balance while calling pair.
emit LiquidityAddition(msg.sender, msg.value);
}
// Possible ways this could break addressed
// 1) Accessing before event is over and resetting eth contributed -- added require
// 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool
// 3) LP per unit is 0 - impossible checked at generation function
function claimLPTokens() public {
require(LPGenerationCompleted, "Event not over yet");
require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along");
IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair);
uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18);
pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change
ethContributed[msg.sender] = 0;
emit LPTokenClaimed(msg.sender, amountLPToTransfer);
}
/**
* @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
virtual
override
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount)
public
virtual
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function setShouldTransferChecker(address _transferCheckerAddress)
public
onlyOwner
{
transferCheckerAddress = _transferCheckerAddress;
}
address public transferCheckerAddress;
function setFeeDistributor(address _feeDistributor)
public
onlyOwner
{
feeDistributor = _feeDistributor;
}
address public feeDistributor;
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
(uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount);
// Addressing a broken checker contract
require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?");
_balances[recipient] = _balances[recipient].add(transferToAmount);
emit Transfer(sender, recipient, transferToAmount);
if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){
_balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount);
emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount);
if(feeDistributor != address(0)){
IdfcoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount);
}
}
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// dfcoreToken with Governance.
contract DFCore is NBUNIERC20 {
/**
* @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() public {
initialSetup();
}
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "dfcore::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "dfcore::delegateBySig: invalid nonce");
require(now <= expiry, "dfcore::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, "dfcore::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 dfcore 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, "dfcore::_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;
}
} | Emergency drain in case of a bug Adds all funds to owner to refund people Designed to be as simple as possible | function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner {
(bool success, ) = msg.sender.call.value(address(this).balance)("");
require(success, "Transfer failed.");
_balances[msg.sender] = _balances[address(this)];
_balances[address(this)] = 0;
}
uint256 public totalLPTokensMinted;
uint256 public totalETHContributed;
uint256 public LPperETHUnit;
bool public LPGenerationCompleted;
| 15,072,425 | [
1,
1514,
24530,
15427,
316,
648,
434,
279,
7934,
15605,
777,
284,
19156,
358,
3410,
358,
16255,
16951,
29703,
329,
358,
506,
487,
4143,
487,
3323,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
801,
24530,
26896,
3247,
76,
4436,
48,
18988,
24237,
13842,
1133,
2520,
7387,
1435,
1071,
1338,
5541,
288,
203,
3639,
261,
6430,
2216,
16,
262,
273,
1234,
18,
15330,
18,
1991,
18,
1132,
12,
2867,
12,
2211,
2934,
12296,
13,
2932,
8863,
203,
3639,
2583,
12,
4768,
16,
315,
5912,
2535,
1199,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
70,
26488,
63,
2867,
12,
2211,
13,
15533,
203,
3639,
389,
70,
26488,
63,
2867,
12,
2211,
25887,
273,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
1071,
2078,
48,
1856,
3573,
49,
474,
329,
31,
203,
565,
2254,
5034,
1071,
2078,
1584,
44,
442,
11050,
31,
203,
565,
2254,
5034,
1071,
511,
52,
457,
1584,
44,
2802,
31,
203,
377,
203,
565,
1426,
1071,
511,
52,
13842,
9556,
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
] |
./partial_match/1/0xb489fe2C5FA370C213a7600DFf185695BC4dCd45/sources/TokenVesting.sol | * @title TokenVesting @dev A token holder contract that can release its token balance gradually like a typical vesting scheme, with a cliff and vesting period. Optionally revocable by the owner./ | contract TokenVesting is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 internal vestToken;
uint256 internal tokensToVest = 0;
uint256 internal vestingId = 0;
string private constant INSUFFICIENT_BALANCE = "Insufficient balance";
string private constant INVALID_VESTING_ID = "Invalid vesting id";
string private constant VESTING_ALREADY_RELEASED = "Vesting already released";
string private constant INVALID_BENEFICIARY = "Invalid beneficiary address";
string private constant NOT_VESTED = "Tokens have not vested yet";
struct Vesting {
uint256 releaseTime;
uint256 amount;
address beneficiary;
bool released;
}
mapping(uint256 => Vesting) public vestings;
event TokenVestingReleased(uint256 indexed vestingId, address indexed beneficiary, uint256 amount);
event TokenVestingAdded(uint256 indexed vestingId, address indexed beneficiary, uint256 amount);
event TokenVestingRemoved(uint256 indexed vestingId, address indexed beneficiary, uint256 amount);
constructor(IERC20 _token) public {
require(address(_token) != address(0x0), "Matic token address is not valid");
vestToken = _token;
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1681761600, 1*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1684353600, 91441*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1687032000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1689624000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1692302400, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1694980800, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1697572800, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1700251200, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1702843200, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1705521600, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1708200000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1710705600, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1713384000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1715976000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1718654400, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1721246400, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1723924800, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1726603200, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1729195200, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1731873600, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1734465600, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1737144000, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1739822400, 91442*1e18 );
addVesting(0x58F9b4f2866de84bDB9805112c1D79EBBA90F4aF, 1742241600, 91442*1e18 );
renounceOwnership();
}
function token() public view returns (IERC20) {
return vestToken;
}
function beneficiary(uint256 _vestingId) public view returns (address) {
return vestings[_vestingId].beneficiary;
}
function releaseTime(uint256 _vestingId) public view returns (uint256) {
return vestings[_vestingId].releaseTime;
}
function vestingAmount(uint256 _vestingId) public view returns (uint256) {
return vestings[_vestingId].amount;
}
function removeVesting(uint256 _vestingId) public onlyOwner {
Vesting storage vesting = vestings[_vestingId];
require(vesting.beneficiary != address(0x0), INVALID_VESTING_ID);
require(!vesting.released , VESTING_ALREADY_RELEASED);
vesting.released = true;
tokensToVest = tokensToVest.sub(vesting.amount);
emit TokenVestingRemoved(_vestingId, vesting.beneficiary, vesting.amount);
}
function addVesting(address _beneficiary, uint256 _releaseTime, uint256 _amount) public onlyOwner {
require(_beneficiary != address(0x0), INVALID_BENEFICIARY);
tokensToVest = tokensToVest.add(_amount);
vestingId = vestingId.add(1);
vestings[vestingId] = Vesting({
beneficiary: _beneficiary,
releaseTime: _releaseTime,
amount: _amount,
released: false
});
emit TokenVestingAdded(vestingId, _beneficiary, _amount);
}
function addVesting(address _beneficiary, uint256 _releaseTime, uint256 _amount) public onlyOwner {
require(_beneficiary != address(0x0), INVALID_BENEFICIARY);
tokensToVest = tokensToVest.add(_amount);
vestingId = vestingId.add(1);
vestings[vestingId] = Vesting({
beneficiary: _beneficiary,
releaseTime: _releaseTime,
amount: _amount,
released: false
});
emit TokenVestingAdded(vestingId, _beneficiary, _amount);
}
function release(uint256 _vestingId) public {
Vesting storage vesting = vestings[_vestingId];
require(vesting.beneficiary != address(0x0), INVALID_VESTING_ID);
require(!vesting.released , VESTING_ALREADY_RELEASED);
require(block.timestamp >= vesting.releaseTime, NOT_VESTED);
require(vestToken.balanceOf(address(this)) >= vesting.amount, INSUFFICIENT_BALANCE);
vesting.released = true;
tokensToVest = tokensToVest.sub(vesting.amount);
vestToken.safeTransfer(vesting.beneficiary, vesting.amount);
emit TokenVestingReleased(_vestingId, vesting.beneficiary, vesting.amount);
}
function retrieveExcessTokens(uint256 _amount) public onlyOwner {
require(_amount <= vestToken.balanceOf(address(this)).sub(tokensToVest), INSUFFICIENT_BALANCE);
vestToken.safeTransfer(owner(), _amount);
}
} | 9,192,193 | [
1,
1345,
58,
10100,
225,
432,
1147,
10438,
6835,
716,
848,
3992,
2097,
1147,
11013,
3087,
2544,
1230,
3007,
279,
24917,
331,
10100,
4355,
16,
598,
279,
927,
3048,
471,
331,
10100,
3879,
18,
20720,
5588,
504,
429,
635,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
3155,
58,
10100,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
467,
654,
39,
3462,
2713,
331,
395,
1345,
31,
203,
565,
2254,
5034,
2713,
2430,
774,
58,
395,
273,
374,
31,
203,
565,
2254,
5034,
2713,
331,
10100,
548,
273,
374,
31,
203,
203,
565,
533,
3238,
5381,
2120,
6639,
42,
1653,
7266,
2222,
67,
38,
1013,
4722,
273,
315,
5048,
11339,
11013,
14432,
203,
565,
533,
3238,
5381,
10071,
67,
3412,
882,
1360,
67,
734,
273,
315,
1941,
331,
10100,
612,
14432,
203,
565,
533,
3238,
5381,
776,
11027,
1360,
67,
1013,
20305,
67,
30762,
40,
273,
315,
58,
10100,
1818,
15976,
14432,
203,
565,
533,
3238,
5381,
10071,
67,
38,
1157,
41,
1653,
7266,
6043,
273,
315,
1941,
27641,
74,
14463,
814,
1758,
14432,
203,
565,
533,
3238,
5381,
4269,
67,
3412,
882,
2056,
273,
315,
5157,
1240,
486,
331,
3149,
4671,
14432,
203,
203,
203,
565,
1958,
776,
10100,
288,
203,
3639,
2254,
5034,
3992,
950,
31,
203,
3639,
2254,
5034,
3844,
31,
203,
3639,
1758,
27641,
74,
14463,
814,
31,
203,
3639,
1426,
15976,
31,
203,
565,
289,
203,
565,
2874,
12,
11890,
5034,
516,
776,
10100,
13,
1071,
331,
395,
899,
31,
203,
203,
565,
871,
3155,
58,
10100,
26363,
12,
11890,
5034,
8808,
331,
10100,
548,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3155,
58,
10100,
8602,
2
] |
./full_match/80001/0x966aDcf1E770F05ff45Bbd6e1199f305b8d8D53d/sources/project_/contracts/ARCX.sol | @custom:oz-upgrades-unsafe-allow constructor | constructor() {
_disableInitializers();
}
| 845,964 | [
1,
36,
3662,
30,
11142,
17,
416,
13088,
17,
318,
4626,
17,
5965,
3885,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3885,
1435,
288,
203,
3639,
389,
8394,
4435,
8426,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xcd01d922a7f96Cb660031c7B5dc11CfD2446307f/sources/Users/ricardomarques/dev/workspace/polkamarkets/bepro-js/contracts/PredictionMarketV2.sol | shares held (all outcomes)
| uint256 sharesAvailable; | 5,695,082 | [
1,
30720,
15770,
261,
454,
29867,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
24123,
5268,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x6973165307F00f39AbC1d910286bd15f7fa347bb/sources/BDK.sol | 挖矿 用户分红非交易时段结算当日挖矿BDK数量所有已挖出BDK数量最后100亿销毁 | function mining() public onlyOwner {
autoSetTradeEnabled();
require(!tradeEnabled,"now is limit time");
require(bMineTotal < bMineMax,"up to _bMineMax,stop mining");
uint256 bNum = bPoolTotal.mul(_mineRate()).div(100);
bMineTotal += bNum;
bMineTotal = bMineMax;
transferFrom(address(this), deadWallet, 10000000000* 10**10);
}
| 8,100,980 | [
1,
167,
239,
249,
168,
258,
128,
225,
168,
247,
106,
167,
235,
120,
166,
235,
233,
168,
123,
100,
170,
256,
257,
165,
123,
102,
167,
251,
246,
167,
250,
119,
167,
111,
118,
168,
124,
246,
168,
111,
250,
166,
126,
246,
167,
250,
103,
167,
239,
249,
168,
258,
128,
38,
3398,
167,
248,
113,
170,
234,
242,
167,
236,
227,
167,
255,
236,
166,
120,
115,
167,
239,
249,
166,
234,
123,
38,
3398,
167,
248,
113,
170,
234,
242,
167,
255,
227,
166,
243,
241,
6625,
165,
123,
128,
170,
247,
227,
167,
112,
228,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1131,
310,
1435,
1071,
1338,
5541,
288,
203,
540,
203,
540,
203,
3639,
3656,
694,
22583,
1526,
5621,
203,
3639,
2583,
12,
5,
20077,
1526,
10837,
3338,
353,
1800,
813,
8863,
203,
540,
203,
3639,
2583,
12,
70,
49,
558,
5269,
411,
324,
49,
558,
2747,
10837,
416,
358,
389,
70,
49,
558,
2747,
16,
5681,
1131,
310,
8863,
203,
540,
203,
3639,
2254,
5034,
324,
2578,
273,
324,
2864,
5269,
18,
16411,
24899,
3081,
4727,
1435,
2934,
2892,
12,
6625,
1769,
203,
540,
203,
3639,
324,
49,
558,
5269,
1011,
324,
2578,
31,
203,
540,
203,
5411,
324,
49,
558,
5269,
273,
324,
49,
558,
2747,
31,
203,
2398,
203,
5411,
7412,
1265,
12,
2867,
12,
2211,
3631,
8363,
16936,
16,
2130,
12648,
14,
1728,
636,
2163,
1769,
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,
-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/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './interface/ITreasurer.sol';
import './GoonToken.sol';
import 'hardhat/console.sol';
// MasterGoon is the master of Goon. He manages Goon and is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once GOON is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug free.
contract MasterGoon is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
modifier onlyDev {
require(msg.sender == dev, "MasterGoon Dev: caller is not the dev");
_;
}
modifier onlyFeeCollector {
require(
msg.sender == feeCollector,
"MasterGoon Fee Collector: caller is not the fee collector"
);
_;
}
// Category informations
struct CatInfo {
// Allocation points assigned to this category
uint256 allocPoints;
// Total pool allocation points. Must be at all time equal to the sum of all
// pool allocation points in this category.
uint256 totalPoolAllocPoints;
// Name of this category
string name;
}
// User informations
struct UserInfo {
// Amount of tokens deposited
uint256 amount;
// Reward debt.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
uint256 rewardDebt;
// Time at which user can harvest this pool again
uint256 nextHarvestTime;
// Reward that will be unlockable when nextHarvestTime is reached
uint256 lockedReward;
}
// Pool informations
struct PoolInfo {
// Address of this pool's token
IERC20 token;
//Category ID of this pool
uint256 catId;
// Allocation points assigned to this pool
uint256 allocPoints;
// Last block where GOON was distributed.
uint256 lastRewardBlock;
// Accumulated GOON per share, times 1e18. Used for rewardDebt calculations.
uint256 accGoonPerShare;
// Deposit fee for this pool, in basis points (from 0 to 10000)
uint256 depositFeeBP;
// Harvest interval for this pool, in seconds
uint256 harvestInterval;
}
// The following limits exist to ensure that the owner of MasterGoon will
// only modify the contract's settings in a specific range of value, that
// the users can see by themselves at any time.
// Maximum harvest interval that can be set
uint256 public constant MAX_HARVEST_INTERVAL = 24 hours;
// Maximum deposit fee that can be set
uint256 public constant MAX_DEPOSIT_FEE_BP = 400;
// Maximum goon reward per block that can be set
uint256 public constant MAX_GOON_PER_BLOCK = 1e18;
// The informations of each category
CatInfo[] public catInfo;
// The pools in each category. Used in front.
mapping(uint256 => uint256[]) public catPools;
// Total category allocation points. Must be at all time equal to the sum of
// all category allocation points.
uint256 public totalCatAllocPoints = 0;
// The informations of each pool
PoolInfo[] public poolInfo;
// Mapping to keep track of which token has been added, and its index in the
// array.
mapping(address => uint256) public tokensAdded;
// The informations of each user, per pool
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// The GOON token
PolyGoonToken public immutable goon;
// The Treasurer. Handles rewards.
ITreasurer public immutable treasurer;
// GOON minted to devs
uint256 public devGoonPerBlock;
// GOON minted as rewards
uint256 public rewardGoonPerBlock;
// The address to send dev funds to
address public dev;
// The address to send fees to
address public feeCollector;
// Launch block
uint256 public startBlock;
// Farming duration, in blocks
uint256 public farmingDuration;
event CategoryCreate(uint256 id, string indexed name, uint256 allocPoints);
event CategoryEdit(uint256 id, uint256 allocPoints);
event PoolCreate(
address indexed token,
uint256 indexed catId,
uint256 allocPoints,
uint256 depositFeeBP,
uint256 harvestInterval
);
event PoolEdit(
address indexed token,
uint256 indexed catId,
uint256 allocPoints,
uint256 depositFeeBP,
uint256 harvestInterval
);
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 amount,
uint256 fee
);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
constructor(
PolyGoonToken _goon,
ITreasurer _treasurer,
address _dev,
address _feeCollector,
uint256 _initGoonPerBlock,
uint256 _startBlock,
uint256 _farmingDuration
) {
goon = _goon;
treasurer = _treasurer;
require(
_initGoonPerBlock <= MAX_GOON_PER_BLOCK,
"MasterGoon: too high goon reward"
);
devGoonPerBlock = _initGoonPerBlock / 10;
rewardGoonPerBlock = _initGoonPerBlock - devGoonPerBlock;
require(
_dev != address(0),
"MasterGoon Dev: null address not permitted"
);
dev = _dev;
require(
_feeCollector != address(0),
"MasterGoon Fee Collector: null address not permitted"
);
feeCollector = _feeCollector;
startBlock = _startBlock;
if (startBlock < block.number) {
startBlock = block.number;
}
require(
_farmingDuration * MAX_GOON_PER_BLOCK <= _goon.maxSupply() - _goon.totalMinted(),
"MasterGoon: farming could go above GOON's max supply"
);
farmingDuration = _farmingDuration;
}
// Update the starting block. Can only be called by the owner.
// Can only be called before current starting block.
// Can only be called if there is no pool registered.
function updateStartBlock(uint256 _newStartBlock) external onlyOwner {
require(
block.number < startBlock,
'MasterGoon: Cannot change startBlock after farming has already started.'
);
require(
poolInfo.length == 0,
'MasterGoon: Cannot change startBlock after a pool has been registered.'
);
require(
_newStartBlock > block.number,
'MasterGoon: Cannot change startBlock with a past block.'
);
startBlock = _newStartBlock;
}
// Update the dev address. Can only be called by the dev.
function updateDev(address _newDev) onlyDev public {
require(
_newDev != address(0),
"MasterGoon Dev: null address not permitted"
);
dev = _newDev;
}
// Update the fee address. Can only be called by the fee collector.
function updateFeeCollector(address _newFeeCollector) onlyFeeCollector public {
require(
_newFeeCollector != address(0),
"MasterGoon Fee Collector: null address not permitted"
);
feeCollector = _newFeeCollector;
}
// Update the goon per block reward. Can only be called by the owner.
function updateGoonPerBlock(uint256 _newGoonPerBlock, bool _withUpdate) onlyOwner public {
require(
_newGoonPerBlock <= MAX_GOON_PER_BLOCK,
"MasterGoon: too high goon reward"
);
if (_withUpdate) {
massUpdatePools();
}
devGoonPerBlock = _newGoonPerBlock / 10;
rewardGoonPerBlock = _newGoonPerBlock - devGoonPerBlock;
}
// View function to check the total goon generated every block
function goonPerBlock() public view returns (uint256) {
return devGoonPerBlock + rewardGoonPerBlock;
}
// View function to check if user can harvest pool
function canHarvest(
uint256 _poolId,
address _user
) public view returns (bool) {
return block.timestamp >= userInfo[_poolId][_user].nextHarvestTime;
}
// Create a new pool category. Can only be called by the owner.
function createCategory(
string calldata _name,
uint256 _allocPoints,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalCatAllocPoints += _allocPoints;
catInfo.push(CatInfo({
name: _name,
allocPoints: _allocPoints,
totalPoolAllocPoints: 0
}));
emit CategoryCreate(catInfo.length - 1, _name, _allocPoints);
}
// Edit a pool category. Can only be called by the owner.
function editCategory(
uint256 _catId,
uint256 _allocPoints,
bool _withUpdate
) public onlyOwner {
require(_catId < catInfo.length, "MasterGoon: category does not exist");
if (_withUpdate) {
massUpdatePools();
}
totalCatAllocPoints =
totalCatAllocPoints - catInfo[_catId].allocPoints + _allocPoints;
catInfo[_catId].allocPoints = _allocPoints;
emit CategoryEdit(_catId, _allocPoints);
}
// Create a new token pool, after checking that it doesn't already exist.
// Can only be called by owner.
function createPool(
uint256 _catId,
IERC20 _token,
uint256 _allocPoints,
uint256 _depositFeeBP,
uint256 _harvestInterval,
bool _withUpdate
) public onlyOwner {
require(_catId < catInfo.length, "MasterGoon: category does not exist");
require(
_harvestInterval <= MAX_HARVEST_INTERVAL,
"MasterGoon: too high harvest interval"
);
require(
_depositFeeBP <= MAX_DEPOSIT_FEE_BP,
"MasterGoon: too high deposit fee"
);
address tokenAddress = address(_token);
require(tokensAdded[tokenAddress] == 0, "MasterGoon: token already registered");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
catInfo[_catId].totalPoolAllocPoints += _allocPoints;
tokensAdded[tokenAddress] = poolInfo.length + 1;
poolInfo.push(PoolInfo({
catId: _catId,
token: _token,
allocPoints: _allocPoints,
lastRewardBlock: lastRewardBlock,
accGoonPerShare: 0,
depositFeeBP: _depositFeeBP,
harvestInterval: _harvestInterval
}));
catPools[_catId].push(poolInfo.length - 1);
emit PoolCreate(
tokenAddress,
_catId,
_allocPoints,
_depositFeeBP,
_harvestInterval
);
}
// Edits a new token pool. Can only be called by owner.
function editPool(
uint256 _poolId,
uint256 _allocPoints,
uint256 _depositFeeBP,
uint256 _harvestInterval,
bool _withUpdate
) public onlyOwner {
require(_poolId < poolInfo.length, "MasterGoon: pool does not exist");
require(
_harvestInterval <= MAX_HARVEST_INTERVAL,
"MasterGoon: too high harvest interval"
);
require(
_depositFeeBP <= MAX_DEPOSIT_FEE_BP,
"MasterGoon: too high deposit fee"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 catId = poolInfo[_poolId].catId;
catInfo[catId].totalPoolAllocPoints =
catInfo[catId].totalPoolAllocPoints - poolInfo[_poolId].allocPoints + _allocPoints;
poolInfo[_poolId].allocPoints = _allocPoints;
poolInfo[_poolId].depositFeeBP = _depositFeeBP;
poolInfo[_poolId].harvestInterval = _harvestInterval;
emit PoolEdit(
address(poolInfo[_poolId].token),
poolInfo[_poolId].catId,
_allocPoints,
_depositFeeBP,
_harvestInterval
);
}
function getMultiplier(
uint256 _from,
uint256 _to
) public view returns (uint256) {
uint256 _endBlock = endBlock();
if (_from >= _endBlock) {
return 0;
}
if (_to > _endBlock) {
return _endBlock - _from;
}
return _to - _from;
}
// Internal function to dispatch pool reward for sender.
// Does one of two things:
// - Reward the user through treasurer
// - Lock up rewards for later harvest
function _dispatchReward(uint256 _poolId) internal {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
if (user.nextHarvestTime == 0) {
user.nextHarvestTime = block.timestamp + pool.harvestInterval;
}
uint256 pending =
user.amount * pool.accGoonPerShare / 1e18 - user.rewardDebt;
if (block.timestamp >= user.nextHarvestTime) {
if (pending > 0 || user.lockedReward > 0) {
uint256 totalReward = pending + user.lockedReward;
user.lockedReward = 0;
user.nextHarvestTime = block.timestamp + pool.harvestInterval;
treasurer.rewardUser(msg.sender, totalReward);
}
} else if (pending > 0) {
user.lockedReward += pending;
}
}
// Deposits tokens into a pool.
function deposit(uint256 _poolId, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_poolId];
require(pool.allocPoints != 0, "MasterGoon Deposit: pool is disabled");
require(
catInfo[pool.catId].allocPoints != 0,
"MasterGoon Deposit: category is disabled"
);
UserInfo storage user = userInfo[_poolId][msg.sender];
updatePool(_poolId);
_dispatchReward(_poolId);
uint256 depositFee = _amount * pool.depositFeeBP / 1e4;
if (_amount > 0) {
pool.token.safeTransferFrom(
msg.sender,
address(this),
_amount
);
if (pool.depositFeeBP > 0) {
pool.token.safeTransfer(feeCollector, depositFee);
user.amount += _amount - depositFee;
}
else {
user.amount += _amount;
}
user.nextHarvestTime = block.timestamp + pool.harvestInterval;
}
user.rewardDebt = user.amount * pool.accGoonPerShare / 1e18;
emit Deposit(msg.sender, _poolId, _amount, depositFee);
}
// Withdraw tokens from a pool.
function withdraw(uint256 _poolId, uint256 _amount) public nonReentrant {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
require(user.amount >= _amount, "MasterGoon: bad withdrawal");
updatePool(_poolId);
_dispatchReward(_poolId);
user.amount -= _amount;
user.rewardDebt = user.amount * pool.accGoonPerShare / 1e18;
if (_amount > 0) {
pool.token.safeTransfer(msg.sender, _amount);
}
emit Withdraw(msg.sender, _poolId, _amount);
}
// EMERGENCY ONLY. Withdraw tokens, give rewards up.
function emergencyWithdraw(uint256 _poolId) public nonReentrant {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][msg.sender];
pool.token.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _poolId, user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.lockedReward = 0;
user.nextHarvestTime = 0;
}
// Update all pool at ones. Watch gas spendings.
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 poolId = 0; poolId < length; poolId++) {
updatePool(poolId);
}
}
// Update a single pool's reward variables, and mints rewards.
// If the pool has no tokenSupply, then the reward will be fully sent to the
// dev fund. This is done so that the amount of tokens minted every block
// is stable, and the end of farming is predictable and only impacted by
// updateGoonPerBlock.
function updatePool(uint256 _poolId) public {
PoolInfo storage pool = poolInfo[_poolId];
if (block.number <= pool.lastRewardBlock
|| pool.allocPoints == 0
|| catInfo[pool.catId].allocPoints == 0
) {
return;
}
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (tokenSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if (multiplier == 0) {
pool.lastRewardBlock = block.number;
return;
}
CatInfo storage cat = catInfo[pool.catId];
uint256 userReward = multiplier * rewardGoonPerBlock
* pool.allocPoints / cat.totalPoolAllocPoints
* cat.allocPoints / totalCatAllocPoints;
uint256 devReward = multiplier * devGoonPerBlock
* pool.allocPoints / cat.totalPoolAllocPoints
* cat.allocPoints / totalCatAllocPoints;
pool.lastRewardBlock = block.number;
pool.accGoonPerShare += userReward * 1e18 / tokenSupply;
goon.mint(dev, devReward);
goon.mint(address(treasurer), userReward);
}
function pendingReward(
uint256 _poolId,
address _user
) external view returns(uint256) {
PoolInfo storage pool = poolInfo[_poolId];
UserInfo storage user = userInfo[_poolId][_user];
CatInfo storage cat = catInfo[pool.catId];
uint256 accGoonPerShare = pool.accGoonPerShare;
uint256 tokenSupply = pool.token.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && tokenSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
if (multiplier != 0) {
uint256 userReward = multiplier * rewardGoonPerBlock
* pool.allocPoints / cat.totalPoolAllocPoints
* cat.allocPoints / totalCatAllocPoints;
accGoonPerShare += userReward * 1e18 / tokenSupply;
}
}
return user.amount * accGoonPerShare / 1e18 - user.rewardDebt
+ user.lockedReward;
}
function poolsLength() external view returns(uint256) {
return poolInfo.length;
}
function categoriesLength() external view returns(uint256) {
return catInfo.length;
}
function poolsInCategory(uint256 _catId) external view returns(uint256[] memory) {
return catPools[_catId];
}
function endBlock() public view returns(uint256) {
return startBlock + farmingDuration;
}
} | Maximum deposit fee that can be set | uint256 public constant MAX_DEPOSIT_FEE_BP = 400;
| 5,390,094 | [
1,
13528,
443,
1724,
14036,
716,
848,
506,
444,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
5381,
4552,
67,
1639,
28284,
67,
8090,
41,
67,
30573,
273,
7409,
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
] |
pragma solidity ^0.4.24;
contract HXevents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 P3DAmount,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed roundID,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
// received pot swap deposit
event onPotSwapDeposit
(
uint256 roundID,
uint256 amountAddedToPot
);
}
//==============================================================================
// _ _ _ _|_ _ _ __|_ _ _ _|_ _ .
// (_(_)| | | | (_|(_ | _\(/_ | |_||_) .
//====================================|=========================================
contract modularShort is HXevents {}
contract HX is modularShort {
using SafeMath for *;
using NameFilter for string;
using HXKeysCalcLong for uint256;
address developer_addr = 0xE5Cb34770248B5896dF380704EC19665F9f39634;
address community_addr = 0xb007f725F9260CD57D5e894f3ad33A80F0f02BA3;
address token_community_addr = 0xBEFB937103A56b866B391b4973F9E8CCb44Bb851;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xF7ca07Ff0389d5690EB9306c490842D837A3fA49);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "HX";
string constant public symbol = "HX";
uint256 private rndExtra_ = 0; // length of the very first ICO
uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
uint256 public rID_; // round id number / total rounds that have happened
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => HXdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => HXdatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
mapping (uint256 => HXdatasets.Round) public round_; // (rID => data) round data
mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id
//****************
// TEAM FEE DATA
//****************
mapping (uint256 => HXdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => HXdatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
// Team allocation structures
// 0 = whales
// 1 = bears
// 2 = sneks
// 3 = bulls
// Team allocation percentages
// (HX, 0) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = HXdatasets.TeamFee(30,6); //46% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[1] = HXdatasets.TeamFee(43,0); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[2] = HXdatasets.TeamFee(56,10); //20% to pot, 20% to aff, 2% to com, 2% to air drop pot
fees_[3] = HXdatasets.TeamFee(43,8); //33% to pot, 20% to aff, 2% to com, 2% to air drop pot
// how to split up the final pot based on which team was picked
// (HX, 0)
potSplit_[0] = HXdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 12% to com
potSplit_[1] = HXdatasets.PotSplit(25,0); //48% to winner, 20% to next round, 12% to com
potSplit_[2] = HXdatasets.PotSplit(20,20); //48% to winner, 15% to next round, 12% to com
potSplit_[3] = HXdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 12% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. ");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, 2, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
*/
function buyXid(uint256 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affCode, _team, _eventData_);
}
function buyXaddr(address _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
function buyXname(bytes32 _affCode, uint256 _team)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
HXdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// buy core
buyCore(_pID, _affID, _team, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _team what team is the player playing for?
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affCode, _team, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// verify a valid team was selected
_team = verifyTeam(_team);
// reload core
reLoadCore(_pID, _affID, _team, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// set up our tx event data
HXdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit HXevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit HXevents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit HXevents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
if (_now < round_[_rID].end)
if (_now > round_[_rID].strt + rndGap_)
return( (round_[_rID].end).sub(_now) );
else
return( (round_[_rID].strt + rndGap_).sub(_now) );
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
// if player is winner
if (round_[_rID].plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID, uint256 _rID)
private
view
returns(uint256)
{
return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return eth invested during ICO phase
* @return round id
* @return total keys for round
* @return time round ends
* @return time round started
* @return current pot
* @return current team ID & player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return whales eth in for round
* @return bears eth in for round
* @return sneks eth in for round
* @return bulls eth in for round
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
return
(
round_[_rID].ico, //0
_rID, //1
round_[_rID].keys, //2
round_[_rID].end, //3
round_[_rID].strt, //4
round_[_rID].pot, //5
(round_[_rID].team + (round_[_rID].plyr * 10)), //6
plyr_[round_[_rID].plyr].addr, //7
plyr_[round_[_rID].plyr].name, //8
rndTmEth_[_rID][0], //9
rndTmEth_[_rID][1], //10
rndTmEth_[_rID][2], //11
rndTmEth_[_rID][3], //12
airDropTracker_ + (airDropPot_ * 1000) //13
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash- 0xee0b5d8b
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
// setup local rID
uint256 _rID = rID_;
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID][_rID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID][_rID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// call core
core(_rID, _pID, msg.value, _affID, _team, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_[_rID].end && round_[_rID].ended == false)
{
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, HXdatasets.EventReturns memory _eventData_)
private
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_rID, _pID, _eth, _affID, _team, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_[_rID].end && round_[_rID].ended == false) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit HXevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID);
// set new leaders
if (round_[_rID].plyr != _pID)
round_[_rID].plyr = _pID;
if (round_[_rID].team != _team)
round_[_rID].team = _team;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys);
plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth);
// update round
round_[_rID].keys = _keys.add(round_[_rID].keys);
round_[_rID].eth = _eth.add(round_[_rID].eth);
rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]);
// distribute eth
_eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_);
_eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _team, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast)
private
view
returns(uint256)
{
return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) );
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _rID round ID you want price for
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _rID, uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0)))
return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm..");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of fomo3d
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = PlayerBook.getPlayerID(msg.sender);
bytes32 _name = PlayerBook.getPlayerName(_pID);
uint256 _laff = PlayerBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev checks to make sure user picked a valid team. if not sets team
* to default (sneks)
*/
function verifyTeam(uint256 _team)
private
pure
returns (uint256)
{
if (_team < 0 || _team > 3)
return(2);
else
return(_team);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// if player has played a previous round, move their unmasked earnings
// from that round to gen vault.
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
// update player's last round played
plyr_[_pID].lrnd = rID_;
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(HXdatasets.EventReturns memory _eventData_)
private
returns (HXdatasets.EventReturns)
{
// setup local rID
uint256 _rID = rID_;
// grab our winning player and team id's
uint256 _winPID = round_[_rID].plyr;
uint256 _winTID = round_[_rID].team;
// grab our pot amount
uint256 _pot = round_[_rID].pot;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(48)) / 100;
uint256 _com = (_pot.mul(2) / 100);
uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100;
uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100;
uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)).sub(_p3d);
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_res = _res.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
community_addr.transfer(_com);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
if (_p3d > 0)
token_community_addr.transfer(_p3d);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.P3DAmount = _p3d;
_eventData_.newPot = _res;
// start next round
rID_++;
_rID++;
round_[_rID].strt = now;
round_[_rID].end = now.add(rndInit_).add(rndGap_);
round_[_rID].pot = _res;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID, uint256 _rIDlast)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys, uint256 _rID)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_[_rID].end && round_[_rID].plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_[_rID].end = _newTime;
else
round_[_rID].end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
token_community_addr.transfer(_p3d);
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit HXevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_com = _com.add(_aff);
}
community_addr.transfer(_com);
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
returns(HXdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 2% into airdrop pot
uint256 _air = (_eth / 50);
airDropPot_ = airDropPot_.add(_air);
// update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share))
_eth = _eth.sub(((_eth.mul(24)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, HXdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit HXevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
//==============================================================================
// (~ _ _ _._|_ .
// _)(/_(_|_|| | | \/ .
//====================/=========================================================
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only team just can activate
require(
msg.sender == developer_addr, "only community can activate"
);
// can only be ran once
require(activated_ == false, "shuoha already activated");
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library HXdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 P3DAmount; // amount distributed to p3d
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 lrnd; // last round played
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
uint256 ico; // ICO phase investment
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 team; // tID of team in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
uint256 ico; // total eth sent in during ICO phase
uint256 icoGen; // total eth for gen during ICO phase
uint256 icoAvg; // average key price for ICO phase
}
struct TeamFee {
uint256 gen; // % of buy in thats paid to key holders of current round
uint256 p3d; // % of buy in thats paid to p3d holders
}
struct PotSplit {
uint256 gen; // % of pot thats paid to key holders of current round
uint256 p3d; // % of pot thats paid to p3d holders
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library HXKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(156250000000000000000000000)).add(1406247070314025878906250000000000000000000000000000000000000000)).sqrt()).sub(37499960937500000000000000000000)) / (78125000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((39062500).mul(_keys.sq()).add(((74999921875000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface PlayerBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @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, "SafeMath mul failed");
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, "SafeMath sub failed");
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, "SafeMath add failed");
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);
}
}
} | * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 @return earnings in wei format/ update gen vault from vaults | function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
updateGenVault(_pID, plyr_[_pID].lrnd);
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
| 88,536 | [
1,
25428,
731,
640,
23455,
425,
1303,
899,
16,
473,
9229,
425,
1303,
899,
16,
1678,
2182,
777,
358,
374,
327,
425,
1303,
899,
316,
732,
77,
740,
19,
1089,
3157,
9229,
628,
9229,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
41,
1303,
899,
12,
11890,
5034,
389,
84,
734,
13,
203,
3639,
3238,
203,
3639,
1135,
12,
11890,
5034,
13,
203,
565,
288,
203,
3639,
1089,
7642,
12003,
24899,
84,
734,
16,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
10826,
4880,
1769,
203,
540,
203,
3639,
2254,
5034,
389,
73,
1303,
899,
273,
261,
1283,
86,
67,
63,
67,
84,
734,
8009,
8082,
2934,
1289,
12,
1283,
86,
67,
63,
67,
84,
734,
8009,
4507,
2934,
1289,
12,
1283,
86,
67,
63,
67,
84,
734,
8009,
7329,
1769,
203,
3639,
309,
261,
67,
73,
1303,
899,
405,
374,
13,
203,
3639,
288,
203,
5411,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
8082,
273,
374,
31,
203,
5411,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
4507,
273,
374,
31,
203,
5411,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
7329,
273,
374,
31,
203,
3639,
289,
203,
203,
3639,
327,
24899,
73,
1303,
899,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xeBB59817E608E4d994D09C5f1432325285500dA1/sources/contracts/defi.sol | Some test functions to view | function setPriceOfETH(uint256 price) public {
rateOfEth = price;
}
| 1,903,770 | [
1,
17358,
1842,
4186,
358,
1476,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
5147,
951,
1584,
44,
12,
11890,
5034,
6205,
13,
1071,
288,
203,
3639,
4993,
951,
41,
451,
273,
6205,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.2;
//new things
contract Old{
address payable owner;
bytes32 bytesnum;
bytes32 hashnum;
//function that has same name with contract's
//is deprecated
constructor(uint256 num) public{
owner = msg.sender;
//sha3 is deprecated
bytesnum =keccak256(abi.encode(num));
//var is deprecated
uint8 a = 0;
//block.blockhash is deprecated
hashnum = blockhash(num);
}
//constant is deprecated
function getOwner() view public returns(address){
return owner;
}
function callAnother() public{
bool flag;
bytes memory data;
(flag, data) = owner.call("");
//callcode and throw are deprecated
if(flag){
revert();
}
else{
//suicide is deprecated
require(msg.sender == owner);
selfdestruct(owner);
}
}
fallback () external{
//msg.gas is deprecated
uint remainGas = gasleft();
if(remainGas > 2300){
revert();
}
}
} | function that has same name with contract'sis deprecated | contract Old{
address payable owner;
bytes32 bytesnum;
bytes32 hashnum;
constructor(uint256 num) public{
owner = msg.sender;
bytesnum =keccak256(abi.encode(num));
uint8 a = 0;
hashnum = blockhash(num);
}
function getOwner() view public returns(address){
return owner;
}
function callAnother() public{
bool flag;
bytes memory data;
(flag, data) = owner.call("");
if(flag){
revert();
}
else{
require(msg.sender == owner);
selfdestruct(owner);
}
}
function callAnother() public{
bool flag;
bytes memory data;
(flag, data) = owner.call("");
if(flag){
revert();
}
else{
require(msg.sender == owner);
selfdestruct(owner);
}
}
function callAnother() public{
bool flag;
bytes memory data;
(flag, data) = owner.call("");
if(flag){
revert();
}
else{
require(msg.sender == owner);
selfdestruct(owner);
}
}
fallback () external{
uint remainGas = gasleft();
if(remainGas > 2300){
revert();
}
}
fallback () external{
uint remainGas = gasleft();
if(remainGas > 2300){
revert();
}
}
} | 13,037,773 | [
1,
915,
716,
711,
1967,
508,
598,
6835,
1807,
291,
6849,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
18613,
95,
203,
565,
1758,
8843,
429,
3410,
31,
203,
282,
1731,
1578,
1731,
2107,
31,
203,
282,
1731,
1578,
1651,
2107,
31,
203,
203,
377,
203,
203,
565,
3885,
12,
11890,
5034,
818,
13,
1071,
95,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
4202,
1731,
2107,
273,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
2107,
10019,
203,
3639,
2254,
28,
279,
273,
374,
31,
203,
3639,
1651,
2107,
273,
1203,
2816,
12,
2107,
1769,
203,
565,
289,
203,
377,
203,
565,
445,
13782,
1435,
1476,
1071,
1135,
12,
2867,
15329,
203,
3639,
327,
3410,
31,
203,
565,
289,
203,
377,
203,
565,
445,
745,
37,
24413,
1435,
1071,
95,
203,
3639,
1426,
2982,
31,
203,
3639,
1731,
3778,
501,
31,
203,
3639,
261,
6420,
16,
501,
13,
273,
3410,
18,
1991,
2932,
8863,
203,
3639,
309,
12,
6420,
15329,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
3639,
469,
95,
203,
5411,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
5411,
365,
5489,
8813,
12,
8443,
1769,
203,
3639,
289,
203,
565,
289,
203,
377,
203,
565,
445,
745,
37,
24413,
1435,
1071,
95,
203,
3639,
1426,
2982,
31,
203,
3639,
1731,
3778,
501,
31,
203,
3639,
261,
6420,
16,
501,
13,
273,
3410,
18,
1991,
2932,
8863,
203,
3639,
309,
12,
6420,
15329,
203,
5411,
15226,
5621,
203,
3639,
289,
203,
3639,
469,
95,
203,
5411,
2583,
12,
3576,
18,
15330,
422,
3410,
1769,
203,
5411,
365,
5489,
8813,
12,
8443,
1769,
203,
3639,
289,
203,
2
] |
./full_match/43114/0x9984d70D5Ab32E8e552974A5A24661BFEfE81DbE/sources/contracts/hurricane-core/avax/AvaxPool.sol | Withdraw LP tokens from AvaxPool. | function withdraw(uint256 _pid, uint256 _amount) public notPause validatePool(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (isMultLP(address(pool.lpToken))) {
withdrawHCTAndToken(_pid, _amount, msg.sender);
withdrawHCT(_pid, _amount, msg.sender);
}
}
| 4,582,715 | [
1,
1190,
9446,
511,
52,
2430,
628,
8789,
651,
2864,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
6610,
16,
2254,
5034,
389,
8949,
13,
1071,
486,
19205,
1954,
2864,
24899,
6610,
13,
288,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
3639,
309,
261,
291,
5049,
14461,
12,
2867,
12,
6011,
18,
9953,
1345,
20349,
288,
203,
5411,
598,
9446,
44,
1268,
1876,
1345,
24899,
6610,
16,
389,
8949,
16,
1234,
18,
15330,
1769,
203,
5411,
598,
9446,
44,
1268,
24899,
6610,
16,
389,
8949,
16,
1234,
18,
15330,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./interfaces/IERC721Enumerable.sol";
contract ERC721Enumerable is IERC721Enumerable, ERC721 {
uint256[] private _allTokens;
mapping(uint256 => uint256) private _allTokensIndex;
mapping(address => uint256[]) private _ownedTokens;
mapping(uint256 => uint256) private _ownedTokensIndex;
constructor() {
_registerInterface(
bytes4(keccak256("totalSupply(bytes4)")) ^
bytes4(keccak256("tokenByIndex(bytes4)")) ^
bytes4(keccak256("tokenOfOwnerByIndex(bytes4)"))
);
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256) {
return _allTokens.length;
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external override view returns (uint256) {
require(_index < this.totalSupply(), "global index is out of bounds");
return _allTokens[_index];
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
override
view
returns (uint256)
{
require(
_index < this.balanceOf(_owner),
"owner index is out of bounds"
);
return _ownedTokens[_owner][_index];
}
// A. add Token to the Owner
// B. all tokens to our totalSupply - to allTokens
function _mint(address to, uint256 tokenId) internal override(ERC721) {
super._mint(to, tokenId);
_addTokensToAllTokensEnumeration(tokenId);
_addAllTokensToOwnerEnumeration(to, tokenId);
}
function _addTokensToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _addAllTokensToOwnerEnumeration(address to, uint256 tokenId)
private
{
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
}
| A. add Token to the Owner B. all tokens to our totalSupply - to allTokens | function _mint(address to, uint256 tokenId) internal override(ERC721) {
super._mint(to, tokenId);
_addTokensToAllTokensEnumeration(tokenId);
_addAllTokensToOwnerEnumeration(to, tokenId);
}
| 12,993,651 | [
1,
37,
18,
527,
3155,
358,
326,
16837,
605,
18,
777,
2430,
358,
3134,
2078,
3088,
1283,
300,
358,
777,
5157,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
81,
474,
12,
2867,
358,
16,
2254,
5034,
1147,
548,
13,
2713,
3849,
12,
654,
39,
27,
5340,
13,
288,
203,
3639,
2240,
6315,
81,
474,
12,
869,
16,
1147,
548,
1769,
203,
203,
3639,
389,
1289,
5157,
774,
1595,
5157,
21847,
12,
2316,
548,
1769,
203,
3639,
389,
1289,
1595,
5157,
774,
5541,
21847,
12,
869,
16,
1147,
548,
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
] |
/*
* PAT Token Sale Smart Contract. Copyright © 2017 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.4.11;
import "./Token.sol";
import "./AbstractContinuousSale.sol";
/**
* Continuous Sale Action for selling PAT tokens.
*/
contract PATTokenSale is AbstractContinuousSale {
/**
* Create PAT Token Sale smart contract with given sale start time, invitation
* signer address, token contract and central bank address.
*
* @param _saleStartTime sale start time
* @param _invitationSigner address of invitation signer
* @param _token ERC20 smart contract managing tokens to be sold
* @param _centralBank central bank address to transfer tokens from
*/
function PATTokenSale (
uint256 _saleStartTime, address _invitationSigner,
Token _token, address _centralBank) {
if (_invitationSigner == 0) revert ();
owner = msg.sender;
saleStartTime = _saleStartTime;
invitationSigner = _invitationSigner;
token = _token;
centralBank = _centralBank;
}
/**
* Place buy-side order at given price. Value sent within transaction should
* be factor of given price and order amount is calculated as msg.value/price.
*
* @param _price order price
* @return true on success, false on error
*/
function placeOrder (uint256 _price) payable returns (bool success) {
if (now < safeAdd (saleStartTime, 48 hours)) revert ();
else return AbstractContinuousSale.placeOrder (_price);
}
/**
* Place buy-side presale order at given price. Value sent within transaction
* should be factor of given price and order amount is calculated as
* msg.value/price.
*
* @param _price order price
* @param _invitation presale invitation
* @return true on success, false on error
*/
function placePresaleOrder (uint256 _price, bytes _invitation)
payable returns (bool success) {
if (now < saleStartTime) revert ();
else if (_invitation.length != 65) revert ();
else {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_invitation, 32))
s := mload(add(_invitation, 64))
v := and(mload(add(_invitation, 65)), 255)
}
if (v < 27) v += 27;
bytes memory prefix = "\x19Ethereum Signed Message:\n20";
if (ecrecover(sha3 (prefix, msg.sender), v, r, s) != invitationSigner) revert ();
else return AbstractContinuousSale.placeOrder (_price);
}
}
/**
* Calculate maximum amount of assets to be sold by given time.
*
* @param _time time to calculate maximum amount of assets to be sole by
* @return maximum amount of assets to be sold by given time
*/
function amountToSellBy (uint256 _time)
constant returns (uint256 amount) {
if (_time < saleStartTime) return 0; // nothing to sell before sale start
_time = safeSub (_time, saleStartTime);
if (_time < 2 days) return 0; // Nothing to sell in first two days
_time = safeSub (_time, 2 days);
if (_time < 28 days)
return safeAdd (840e6, safeMul (_time, 3360e6) / 28 days);
_time = safeSub (_time, 28 days);
if (_time < 720 days)
return safeAdd (4200e6, safeMul (_time, 10080e6) / 720 days);
return 14280e6;
}
/**
* Send given amount of assets to the owner of given address.
*
* @param _to address to send assets to the owner of
* @param _amount amount of assets to send
* @return true on success, false on error
*/
function sendAssets (address _to, uint256 _amount)
internal returns (bool success) {
return token.transferFrom (centralBank, _to, _amount);
}
/**
* Collect sale revenue and send it to the owner of smart contract.
*
* @return true on success, false on fail
*/
function collectRevenue () returns (bool success) {
if (msg.sender != owner) revert ();
uint256 revenue = outstandingRevenue (now);
if (revenue > 0)
return msg.sender.send (revenue);
else return true;
}
/**
* Set new owner for this smart contract.
*
* @param _newOwner address of the new owner
*/
function setOwner (address _newOwner) {
if (msg.sender != owner) revert ();
owner = _newOwner;
}
/**
* Address of the owner of smart contract.
*/
address private owner;
/**
* Sale start time.
*/
uint256 private saleStartTime;
/**
* Address of invitation signer.
*/
address private invitationSigner;
/**
* ERC20 token smart contract managing tokens to be sold.
*/
Token private token;
/**
* Address of central bank to transfer tokens from.
*/
address private centralBank;
}
| * Send given amount of assets to the owner of given address. @param _to address to send assets to the owner of @param _amount amount of assets to send @return true on success, false on error/ | function sendAssets (address _to, uint256 _amount)
internal returns (bool success) {
return token.transferFrom (centralBank, _to, _amount);
}
| 2,503,059 | [
1,
3826,
864,
3844,
434,
7176,
358,
326,
3410,
434,
864,
1758,
18,
225,
389,
869,
1758,
358,
1366,
7176,
358,
326,
3410,
434,
225,
389,
8949,
3844,
434,
7176,
358,
1366,
327,
638,
603,
2216,
16,
629,
603,
555,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
1366,
10726,
261,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
203,
565,
2713,
1135,
261,
6430,
2216,
13,
288,
203,
565,
327,
1147,
18,
13866,
1265,
261,
71,
12839,
16040,
16,
389,
869,
16,
389,
8949,
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
] |
./full_match/5/0x81c7a9d494c74F113cCa32d174925352bD3875f1/sources/_connext/nxtp-contracts/contracts/nomad-core/contracts/Home.sol | * @notice Set a new Updater @param _updater the new Updater/ | function setUpdater(address _updater) external onlyUpdaterManager {
_setUpdater(_updater);
}
| 1,910,425 | [
1,
694,
279,
394,
27254,
2045,
225,
389,
25575,
326,
394,
27254,
2045,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
444,
15305,
12,
2867,
389,
25575,
13,
3903,
1338,
15305,
1318,
288,
203,
565,
389,
542,
15305,
24899,
25575,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: localhost/contracts/handlers/curve/IOneSplit.sol
pragma solidity ^0.5.0;
interface IOneSplit {
function getExpectedReturn(
address fromToken,
address toToken,
uint256 amount,
uint256 parts,
uint256 featureFlags
)
external
view
returns (uint256 returnAmount, uint256[] memory distribution);
function swap(
address fromToken,
address toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 featureFlags
) external payable;
}
// File: localhost/contracts/handlers/curve/ICurveDeposit.sol
pragma solidity ^0.5.0;
// Curve compound, y, busd, pax and susd pools have this wrapped contract called
// deposit used to manipulate liquidity.
interface ICurveDeposit {
function underlying_coins(int128 arg0) external view returns (address);
function token() external view returns (address);
// compound pool
function add_liquidity(
uint256[2] calldata uamounts,
uint256 min_mint_amount
) external;
// usdt(deprecated) pool
function add_liquidity(
uint256[3] calldata uamounts,
uint256 min_mint_amount
) external;
// y, busd and pax pools
function add_liquidity(
uint256[4] calldata uamounts,
uint256 min_mint_amount
) external;
// compound, y, busd, pax and susd pools
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_uamount,
bool donate_dust
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
}
// File: localhost/contracts/handlers/curve/ICurveSwap.sol
pragma solidity ^0.5.0;
interface ICurveSwap {
function coins(int128 arg0) external view returns (address);
function underlying_coins(int128 arg0) external view returns (address);
function get_dy(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function exchange(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
function get_dy_underlying(
int128 i,
int128 j,
uint256 dx
) external view returns (uint256);
function exchange_underlying(
int128 i,
int128 j,
uint256 dx,
uint256 min_dy
) external;
// ren pool
function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount)
external;
// sbtc pool
function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount)
external;
// susd pool
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)
external;
function calc_token_amount(uint256[2] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[3] calldata amounts, bool deposit)
external
view
returns (uint256);
function calc_token_amount(uint256[4] calldata amounts, bool deposit)
external
view
returns (uint256);
// Curve ren and sbtc pools
function remove_liquidity_one_coin(
uint256 _token_amount,
int128 i,
uint256 min_amount
) external;
function calc_withdraw_one_coin(uint256 _token_amount, int128 i)
external
view
returns (uint256);
}
// File: localhost/contracts/Config.sol
pragma solidity ^0.5.0;
contract Config {
// function signature of "postProcess()"
bytes4 constant POSTPROCESS_SIG = 0xc2722916;
// Handler post-process type. Others should not happen now.
enum HandlerType {Token, Custom, Others}
}
// File: localhost/contracts/lib/LibCache.sol
pragma solidity ^0.5.0;
library LibCache {
function setAddress(bytes32[] storage _cache, address _input) internal {
_cache.push(bytes32(uint256(uint160(_input))));
}
function set(bytes32[] storage _cache, bytes32 _input) internal {
_cache.push(_input);
}
function setHandlerType(bytes32[] storage _cache, uint256 _input) internal {
require(_input < uint96(-1), "Invalid Handler Type");
_cache.push(bytes12(uint96(_input)));
}
function setSender(bytes32[] storage _cache, address _input) internal {
require(_cache.length == 0, "cache not empty");
setAddress(_cache, _input);
}
function getAddress(bytes32[] storage _cache)
internal
returns (address ret)
{
ret = address(uint160(uint256(peek(_cache))));
_cache.pop();
}
function getSig(bytes32[] storage _cache) internal returns (bytes4 ret) {
ret = bytes4(peek(_cache));
_cache.pop();
}
function get(bytes32[] storage _cache) internal returns (bytes32 ret) {
ret = peek(_cache);
_cache.pop();
}
function peek(bytes32[] storage _cache)
internal
view
returns (bytes32 ret)
{
require(_cache.length > 0, "cache empty");
ret = _cache[_cache.length - 1];
}
function getSender(bytes32[] storage _cache)
internal
returns (address ret)
{
require(_cache.length > 0, "cache empty");
ret = address(uint160(uint256(_cache[0])));
}
}
// File: localhost/contracts/Cache.sol
pragma solidity ^0.5.0;
/// @notice A cache structure composed by a bytes32 array
contract Cache {
using LibCache for bytes32[];
bytes32[] cache;
modifier isCacheEmpty() {
require(cache.length == 0, "Cache not empty");
_;
}
}
// File: localhost/contracts/handlers/HandlerBase.sol
pragma solidity ^0.5.0;
contract HandlerBase is Cache, Config {
function postProcess() external payable {
revert("Invalid post process");
/* Implementation template
bytes4 sig = cache.getSig();
if (sig == bytes4(keccak256(bytes("handlerFunction_1()")))) {
// Do something
} else if (sig == bytes4(keccak256(bytes("handlerFunction_2()")))) {
bytes32 temp = cache.get();
// Do something
} else revert("Invalid post process");
*/
}
function _updateToken(address token) internal {
cache.setAddress(token);
// Ignore token type to fit old handlers
// cache.setHandlerType(uint256(HandlerType.Token));
}
function _updatePostProcess(bytes32[] memory params) internal {
for (uint256 i = params.length; i > 0; i--) {
cache.set(params[i - 1]);
}
cache.set(msg.sig);
cache.setHandlerType(uint256(HandlerType.Custom));
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: localhost/contracts/handlers/curve/HCurve.sol
pragma solidity ^0.5.0;
contract HCurve is HandlerBase {
using SafeERC20 for IERC20;
address public constant ONE_SPLIT = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E;
// Curve fixed input used for susd, ren and sbtc pools
function exchange(
address swap,
int128 i,
int128 j,
uint256 dx,
uint256 minDy
) external payable {
ICurveSwap curveSwap = ICurveSwap(swap);
IERC20(curveSwap.coins(i)).safeApprove(address(curveSwap), dx);
curveSwap.exchange(i, j, dx, minDy);
IERC20(curveSwap.coins(i)).safeApprove(address(curveSwap), 0);
_updateToken(curveSwap.coins(j));
}
// Curve fixed input used for compound, y, busd and pax pools
function exchangeUnderlying(
address swap,
int128 i,
int128 j,
uint256 dx,
uint256 minDy
) external payable {
ICurveSwap curveSwap = ICurveSwap(swap);
IERC20(curveSwap.underlying_coins(i)).safeApprove(
address(curveSwap),
dx
);
curveSwap.exchange_underlying(i, j, dx, minDy);
IERC20(curveSwap.underlying_coins(i)).safeApprove(
address(curveSwap),
0
);
_updateToken(curveSwap.underlying_coins(j));
}
// OneSplit fixed input used for Curve swap
function swap(
address fromToken,
address toToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 featureFlags
) external payable {
IOneSplit oneSplit = IOneSplit(ONE_SPLIT);
IERC20(fromToken).safeApprove(address(oneSplit), amount);
oneSplit.swap(
fromToken,
toToken,
amount,
minReturn,
distribution,
featureFlags
);
IERC20(fromToken).safeApprove(address(oneSplit), 0);
_updateToken(toToken);
}
// Curve add liquidity used for susd, ren and sbtc pools which don't use
// underlying tokens.
function addLiquidity(
address swapAddress,
address pool,
uint256[] calldata amounts,
uint256 minMintAmount
) external payable {
ICurveSwap curveSwap = ICurveSwap(swapAddress);
// Approve non-zero amount erc20 token
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] == 0) continue;
IERC20(curveSwap.coins(int128(i))).safeApprove(
address(curveSwap),
amounts[i]
);
}
// Execute add_liquidity according to amount array size
if (amounts.length == 4) {
uint256[4] memory amts = [
amounts[0],
amounts[1],
amounts[2],
amounts[3]
];
curveSwap.add_liquidity(amts, minMintAmount);
} else if (amounts.length == 3) {
uint256[3] memory amts = [amounts[0], amounts[1], amounts[2]];
curveSwap.add_liquidity(amts, minMintAmount);
} else if (amounts.length == 2) {
uint256[2] memory amts = [amounts[0], amounts[1]];
curveSwap.add_liquidity(amts, minMintAmount);
} else {
revert("invalid amount array size");
}
// Reset zero amount for approval
for (uint256 i = 0; i < amounts.length; i++) {
if (amounts[i] == 0) continue;
IERC20(curveSwap.coins(int128(i))).safeApprove(
address(curveSwap),
0
);
}
// Update post process
_updateToken(address(pool));
}
// Curve add liquidity used for compound, y, busd and pax pools using
// zap which is wrapped contract called deposit.
function addLiquidityZap(
address deposit,
uint256[] calldata uamounts,
uint256 minMintAmount
) external payable {
ICurveDeposit curveDeposit = ICurveDeposit(deposit);
// Approve non-zero amount erc20 token
for (uint256 i = 0; i < uamounts.length; i++) {
if (uamounts[i] == 0) continue;
IERC20(curveDeposit.underlying_coins(int128(i))).safeApprove(
address(curveDeposit),
uamounts[i]
);
}
// Execute add_liquidity according to uamount array size
if (uamounts.length == 4) {
uint256[4] memory amts = [
uamounts[0],
uamounts[1],
uamounts[2],
uamounts[3]
];
curveDeposit.add_liquidity(amts, minMintAmount);
} else if (uamounts.length == 3) {
uint256[3] memory amts = [uamounts[0], uamounts[1], uamounts[2]];
curveDeposit.add_liquidity(amts, minMintAmount);
} else if (uamounts.length == 2) {
uint256[2] memory amts = [uamounts[0], uamounts[1]];
curveDeposit.add_liquidity(amts, minMintAmount);
} else {
revert("invalid uamount array size");
}
// Reset zero amount for approval
for (uint256 i = 0; i < uamounts.length; i++) {
if (uamounts[i] == 0) continue;
IERC20(curveDeposit.underlying_coins(int128(i))).safeApprove(
address(curveDeposit),
0
);
}
// Update post process
_updateToken(curveDeposit.token());
}
// Curve remove liquidity one coin used for ren and sbtc pools which don't
// use underlying tokens.
function removeLiquidityOneCoin(
address swapAddress,
address pool,
uint256 tokenAmount,
int128 i,
uint256 minAmount
) external payable {
ICurveSwap curveSwap = ICurveSwap(swapAddress);
IERC20(pool).safeApprove(address(curveSwap), tokenAmount);
curveSwap.remove_liquidity_one_coin(tokenAmount, i, minAmount);
IERC20(pool).safeApprove(address(curveSwap), 0);
// Update post process
_updateToken(curveSwap.coins(i));
}
// Curve remove liquidity one coin used for compound, y, busd, pax and susd
// pools using zap which is wrapped contract called deposit. Note that if we
// use susd remove_liquidity_one_coin() it must be the one in deposit
// instead of swap contract.
function removeLiquidityOneCoinZap(
address deposit,
uint256 tokenAmount,
int128 i,
uint256 minUamount
) external payable {
ICurveDeposit curveDeposit = ICurveDeposit(deposit);
IERC20(curveDeposit.token()).safeApprove(
address(curveDeposit),
tokenAmount
);
curveDeposit.remove_liquidity_one_coin(
tokenAmount,
i,
minUamount,
true
);
IERC20(curveDeposit.token()).safeApprove(address(curveDeposit), 0);
// Update post process
_updateToken(curveDeposit.underlying_coins(i));
}
} | Curve fixed input used for compound, y, busd and pax pools | function exchangeUnderlying(
address swap,
int128 i,
int128 j,
uint256 dx,
uint256 minDy
) external payable {
ICurveSwap curveSwap = ICurveSwap(swap);
IERC20(curveSwap.underlying_coins(i)).safeApprove(
address(curveSwap),
dx
);
curveSwap.exchange_underlying(i, j, dx, minDy);
IERC20(curveSwap.underlying_coins(i)).safeApprove(
address(curveSwap),
0
);
_updateToken(curveSwap.underlying_coins(j));
}
| 6,787,508 | [
1,
9423,
5499,
810,
1399,
364,
11360,
16,
677,
16,
5766,
72,
471,
293,
651,
16000,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7829,
14655,
6291,
12,
203,
3639,
1758,
7720,
16,
203,
3639,
509,
10392,
277,
16,
203,
3639,
509,
10392,
525,
16,
203,
3639,
2254,
5034,
6633,
16,
203,
3639,
2254,
5034,
1131,
40,
93,
203,
565,
262,
3903,
8843,
429,
288,
203,
3639,
467,
9423,
12521,
8882,
12521,
273,
467,
9423,
12521,
12,
22270,
1769,
203,
3639,
467,
654,
39,
3462,
12,
16683,
12521,
18,
9341,
6291,
67,
71,
9896,
12,
77,
13,
2934,
4626,
12053,
537,
12,
203,
5411,
1758,
12,
16683,
12521,
3631,
203,
5411,
6633,
203,
3639,
11272,
203,
3639,
8882,
12521,
18,
16641,
67,
9341,
6291,
12,
77,
16,
525,
16,
6633,
16,
1131,
40,
93,
1769,
203,
3639,
467,
654,
39,
3462,
12,
16683,
12521,
18,
9341,
6291,
67,
71,
9896,
12,
77,
13,
2934,
4626,
12053,
537,
12,
203,
5411,
1758,
12,
16683,
12521,
3631,
203,
5411,
374,
203,
3639,
11272,
203,
203,
3639,
389,
2725,
1345,
12,
16683,
12521,
18,
9341,
6291,
67,
71,
9896,
12,
78,
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
] |
pragma solidity ^0.4.23;
/*
* Author: Konstantin G...
* Telegram: @bunnygame (en)
* talk : https://bitcointalk.org/index.php?topic=5025885.0
* discord : https://discordapp.com/invite/G2jt4Fw
* email: [email protected]
* site : http://bunnycoin.co
*/
/**
* @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 ownerCEO;
address ownerMoney;
address privAddress;
address addressAdmixture;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
ownerCEO = msg.sender;
ownerMoney = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == ownerCEO);
_;
}
function transferOwnership(address add) public onlyOwner {
if (add != address(0)) {
ownerCEO = add;
}
}
function transferOwnerMoney(address _ownerMoney) public onlyOwner {
if (_ownerMoney != address(0)) {
ownerMoney = _ownerMoney;
}
}
function getOwnerMoney() public view onlyOwner returns(address) {
return ownerMoney;
}
/**
* @dev private contract
*/
function getPrivAddress() public view onlyOwner returns(address) {
return privAddress;
}
function getAddressAdmixture() public view onlyOwner returns(address) {
return addressAdmixture;
}
}
/**
* @title Whitelist
* @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions.
* @dev This simplifies the implementation of "user permissions".
*/
contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
mapping(uint => address) whitelistCheck;
uint public countAddress = 0;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
/**
* @dev Throws if called by any account that's not whitelisted.
*/
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
constructor() public {
whitelist[msg.sender] = true;
whitelist[this] = true;
}
/**
* @dev add an address to the whitelist
* @param addr address
* @return true if the address was added to the whitelist, false if the address was already in the whitelist
*/
function addAddressToWhitelist(address addr) onlyWhitelisted public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
countAddress = countAddress + 1;
whitelistCheck[countAddress] = addr;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
function getWhitelistCheck(uint key) onlyWhitelisted view public returns(address) {
return whitelistCheck[key];
}
function getInWhitelist(address addr) public view returns(bool) {
return whitelist[addr];
}
function getOwnerCEO() public onlyWhitelisted view returns(address) {
return ownerCEO;
}
/**
* @dev add addresses to the whitelist
* @param addrs addresses
* @return true if at least one address was added to the whitelist,
* false if all addresses were already in the whitelist
*/
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
* @return true if the address was removed from the whitelist,
* false if the address wasn't in the whitelist in the first place
*/
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
/**
* @dev remove addresses from the whitelist
* @param addrs addresses
* @return true if at least one address was removed from the whitelist,
* false if all addresses weren't in the whitelist in the first place
*/
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract BaseRabbit is Whitelist {
event EmotherCount(uint32 mother, uint summ);
event SalaryBunny(uint32 bunnyId, uint cost);
event CreateChildren(uint32 matron, uint32 sire, uint32 child);
event BunnyDescription(uint32 bunnyId, string name);
event CoolduwnMother(uint32 bunnyId, uint num);
event Referral(address from, uint32 matronID, uint32 childID, uint currentTime);
event Approval(address owner, address approved, uint32 tokenId);
event Transfer(address from, address to, uint32 tokenId);
event NewBunny(uint32 bunnyId, uint dnk, uint256 blocknumber, uint breed);
using SafeMath for uint256;
bool pauseSave = false;
// ID the last seal
// ID the last seal
bool public promoPause = false;
function setPromoPause() public onlyWhitelisted() {
promoPause = !promoPause;
}
//
// внешняя функция сколько заработала мамочка
mapping(uint32 => uint) public totalSalaryBunny;
// кто мамочка у ребёнка
mapping(uint32 => uint32[5]) public rabbitMother;
// сколько раз стала мамочка текущий кролик
mapping(uint32 => uint) public motherCount;
// сколько стоит скрещивание у кролика
mapping(uint32 => uint) public rabbitSirePrice;
// разрешено ли менять кролику пол
mapping(uint32 => bool) public allowedChangeSex;
// сколько мужиков с текущим геном
// mapping(uint => uint32[]) public sireGenom;
mapping (uint32 => uint) mapDNK;
mapping (uint32 => bool) giffblock;
/**
* Where we will store information about rabbits
*/
// Rabbit[] public rabbits;
mapping (uint32 => Rabbit) tokenBunny;
uint public tokenBunnyTotal;
/**
* who owns the rabbit
*/
mapping (uint32 => address) public rabbitToOwner;
mapping (address => uint32[]) public ownerBunnies;
mapping (address => bool) ownerGennezise;
struct Rabbit {
// parents
uint32 mother;
uint32 sire;
// block in which a rabbit was born
uint birthblock;
// number of births or how many times were offspring
uint birthCount;
// The time when Rabbit last gave birth
uint birthLastTime;
//indexGenome
uint genome;
}
}
/// @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 ownerOf(uint32 _tokenId) public view returns (address owner);
function approve(address _to, uint32 _tokenId) public returns (bool success);
function transfer(address _to, uint32 _tokenId) public;
function transferFrom(address _from, address _to, uint32 _tokenId) public returns (bool);
function totalSupply() public view returns (uint total);
function balanceOf(address _owner) public view returns (uint balance);
}
/// @title Interface new rabbits address
contract PrivateRabbitInterface {
function getNewRabbit(address from) public view returns (uint);
function mixDNK(uint dnkmother, uint dnksire, uint genome) public view returns (uint);
function isUIntPrivate() public pure returns (bool);
}
contract Rabbit is BaseRabbit, ERC721 {
uint public totalBunny = 0;
string public constant name = "CryptoRabbits";
string public constant symbol = "CRB";
function ownerOf(uint32 _tokenId) public view returns (address owner) {
return rabbitToOwner[_tokenId];
}
function approve(address _to, uint32 _tokenId) public returns (bool) {
_to;
_tokenId;
return false;
}
function removeTokenList(address _owner, uint32 _tokenId) internal {
require(isPauseSave());
uint count = ownerBunnies[_owner].length;
for (uint256 i = 0; i < count; i++) {
if(ownerBunnies[_owner][i] == _tokenId)
{
delete ownerBunnies[_owner][i];
if(count > 0 && count != (i-1)){
ownerBunnies[_owner][i] = ownerBunnies[_owner][(count-1)];
delete ownerBunnies[_owner][(count-1)];
}
ownerBunnies[_owner].length--;
return;
}
}
}
/**
* @dev add a new bunny in the storage
*/
function addTokenList(address owner, uint32 _tokenId) internal {
ownerBunnies[owner].push( _tokenId);
rabbitToOwner[_tokenId] = owner;
}
function transfer(address _to, uint32 _tokenId) public {
require(isPauseSave());
address currentOwner = msg.sender;
address oldOwner = rabbitToOwner[_tokenId];
require(rabbitToOwner[_tokenId] == msg.sender);
require(currentOwner != _to);
require(_to != address(0));
removeTokenList(oldOwner, _tokenId);
addTokenList(_to, _tokenId);
emit Transfer(oldOwner, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint32 _tokenId) public onlyWhitelisted() returns(bool) {
require(isPauseSave());
address oldOwner = rabbitToOwner[_tokenId];
require(oldOwner == _from);
require(oldOwner != _to);
require(_to != address(0));
removeTokenList(oldOwner, _tokenId);
addTokenList(_to, _tokenId);
setAllowedChangeSex(_tokenId, false);
emit Transfer (oldOwner, _to, _tokenId);
return true;
}
function isPauseSave() public view returns(bool) {
return !pauseSave;
}
function isPromoPause() public view returns(bool) {
if (getInWhitelist(msg.sender)) {
return true;
} else {
return !promoPause;
}
}
function setPauseSave() public onlyWhitelisted() returns(bool) {
return pauseSave = !pauseSave;
}
function setTotalBunny() internal onlyWhitelisted() returns(uint) {
require(isPauseSave());
return totalBunny = totalBunny.add(1);
}
function setTotalBunny_id(uint _totalBunny) external onlyWhitelisted() {
require(isPauseSave());
totalBunny = _totalBunny;
}
function setTokenBunny(uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, uint genome, address _owner, uint DNK)
external onlyWhitelisted() returns(uint32) {
uint32 id = uint32(setTotalBunny());
tokenBunny[id] = Rabbit(mother, sire, birthblock, birthCount, birthLastTime, genome);
mapDNK[id] = DNK;
addTokenList(_owner, id);
emit NewBunny(id, DNK, block.number, 0);
emit CreateChildren(mother, sire, id);
setMotherCount(id, 0);
return id;
}
// correction of mistakes with parents
function relocateToken(
uint32 id,
uint32 mother,
uint32 sire,
uint birthblock,
uint birthCount,
uint birthLastTime,
uint genome,
address _owner,
uint DNK
) external onlyWhitelisted(){
// if(mapDNK[id] != 0){
tokenBunny[id] = Rabbit(mother, sire, birthblock, birthCount, birthLastTime, genome);
mapDNK[id] = DNK;
addTokenList(_owner, id);
// }
}
function setDNK( uint32 _bunny, uint dnk) external onlyWhitelisted() {
require(isPauseSave());
mapDNK[_bunny] = dnk;
}
function setMotherCount( uint32 _bunny, uint count) public onlyWhitelisted() {
require(isPauseSave());
motherCount[_bunny] = count;
}
function setRabbitSirePrice( uint32 _bunny, uint count) external onlyWhitelisted() {
require(isPauseSave());
rabbitSirePrice[_bunny] = count;
}
function setAllowedChangeSex( uint32 _bunny, bool canBunny) public onlyWhitelisted() {
require(isPauseSave());
allowedChangeSex[_bunny] = canBunny;
}
function setTotalSalaryBunny( uint32 _bunny, uint count) external onlyWhitelisted() {
require(isPauseSave());
totalSalaryBunny[_bunny] = count;
}
function setRabbitMother(uint32 children, uint32[5] _m) external onlyWhitelisted() {
rabbitMother[children] = _m;
}
function setGenome(uint32 _bunny, uint genome) external onlyWhitelisted(){
tokenBunny[_bunny].genome = genome;
}
function setParent(uint32 _bunny, uint32 mother, uint32 sire) external onlyWhitelisted() {
tokenBunny[_bunny].mother = mother;
tokenBunny[_bunny].sire = sire;
}
function setBirthLastTime(uint32 _bunny, uint birthLastTime) external onlyWhitelisted() {
tokenBunny[_bunny].birthLastTime = birthLastTime;
}
function setBirthCount(uint32 _bunny, uint birthCount) external onlyWhitelisted() {
tokenBunny[_bunny].birthCount = birthCount;
}
function setBirthblock(uint32 _bunny, uint birthblock) external onlyWhitelisted() {
tokenBunny[_bunny].birthblock = birthblock;
}
function setGiffBlock(uint32 _bunny, bool blocked) external onlyWhitelisted() {
giffblock[_bunny] = blocked;
}
function setOwnerGennezise(address _to, bool canYou) external onlyWhitelisted() {
ownerGennezise[_to] = canYou;
}
////// getters
function getOwnerGennezise(address _to) public view returns(bool) {
return ownerGennezise[_to];
}
function getGiffBlock(uint32 _bunny) public view returns(bool) {
return !giffblock[_bunny];
}
function getAllowedChangeSex(uint32 _bunny) public view returns(bool) {
return !allowedChangeSex[_bunny];
}
function getRabbitSirePrice(uint32 _bunny) public view returns(uint) {
return rabbitSirePrice[_bunny];
}
function getTokenOwner(address owner) public view returns(uint total, uint32[] list) {
total = ownerBunnies[owner].length;
list = ownerBunnies[owner];
}
function totalSupply() public view returns (uint total) {
return totalBunny;
}
function balanceOf(address _owner) public view returns (uint) {
return ownerBunnies[_owner].length;
}
function getMotherCount(uint32 _mother) public view returns(uint) { //internal
return motherCount[_mother];
}
function getTotalSalaryBunny(uint32 _bunny) public view returns(uint) { //internal
return totalSalaryBunny[_bunny];
}
function getRabbitMother( uint32 mother) public view returns(uint32[5]) {
return rabbitMother[mother];
}
function getRabbitMotherSumm(uint32 mother) public view returns(uint count) { //internal
for (uint m = 0; m < 5 ; m++) {
if(rabbitMother[mother][m] != 0 ) {
count++;
}
}
}
function getDNK(uint32 bunnyid) public view returns(uint) {
return mapDNK[bunnyid];
}
function getTokenBunny(uint32 _bunny) public
view returns(uint32 mother, uint32 sire, uint birthblock, uint birthCount, uint birthLastTime, uint genome) {
mother = tokenBunny[_bunny].mother;
sire = tokenBunny[_bunny].sire;
birthblock = tokenBunny[_bunny].birthblock;
birthCount = tokenBunny[_bunny].birthCount;
birthLastTime = tokenBunny[_bunny].birthLastTime;
genome = tokenBunny[_bunny].genome;
}
function isUIntPublic() public view returns(bool) {
require(isPauseSave());
return true;
}
function getSex(uint32 _bunny) public view returns(bool) {
if(getRabbitSirePrice(_bunny) > 0) {
return true;
}
return false;
}
function getGenome(uint32 _bunny) public view returns( uint) {
return tokenBunny[_bunny].genome;
}
function getParent(uint32 _bunny) public view returns(uint32 mother, uint32 sire) {
mother = tokenBunny[_bunny].mother;
sire = tokenBunny[_bunny].sire;
}
function getBirthLastTime(uint32 _bunny) public view returns(uint) {
return tokenBunny[_bunny].birthLastTime;
}
function getBirthCount(uint32 _bunny) public view returns(uint) {
return tokenBunny[_bunny].birthCount;
}
function getBirthblock(uint32 _bunny) public view returns(uint) {
return tokenBunny[_bunny].birthblock;
}
function getBunnyInfo(uint32 _bunny) public view returns(
uint32 mother,
uint32 sire,
uint birthblock,
uint birthCount,
uint birthLastTime,
bool role,
uint genome,
bool interbreed,
uint leftTime,
uint lastTime,
uint price,
uint motherSumm
) {
role = getSex(_bunny);
mother = tokenBunny[_bunny].mother;
sire = tokenBunny[_bunny].sire;
birthblock = tokenBunny[_bunny].birthblock;
birthCount = tokenBunny[_bunny].birthCount;
birthLastTime = tokenBunny[_bunny].birthLastTime;
genome = tokenBunny[_bunny].genome;
motherSumm = getMotherCount(_bunny);
price = getRabbitSirePrice(_bunny);
lastTime = lastTime.add(birthLastTime);
if(lastTime <= now) {
interbreed = true;
} else {
leftTime = lastTime.sub(now);
}
}
} | * @title Whitelist @dev The Whitelist contract has a whitelist of addresses, and provides basic authorization control functions. @dev This simplifies the implementation of "user permissions"./ | contract Whitelist is Ownable {
mapping(address => bool) public whitelist;
mapping(uint => address) whitelistCheck;
uint public countAddress = 0;
event WhitelistedAddressAdded(address addr);
event WhitelistedAddressRemoved(address addr);
modifier onlyWhitelisted() {
require(whitelist[msg.sender]);
_;
}
constructor() public {
whitelist[msg.sender] = true;
whitelist[this] = true;
}
function addAddressToWhitelist(address addr) onlyWhitelisted public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
countAddress = countAddress + 1;
whitelistCheck[countAddress] = addr;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
function addAddressToWhitelist(address addr) onlyWhitelisted public returns(bool success) {
if (!whitelist[addr]) {
whitelist[addr] = true;
countAddress = countAddress + 1;
whitelistCheck[countAddress] = addr;
emit WhitelistedAddressAdded(addr);
success = true;
}
}
function getWhitelistCheck(uint key) onlyWhitelisted view public returns(address) {
return whitelistCheck[key];
}
function getInWhitelist(address addr) public view returns(bool) {
return whitelist[addr];
}
function getOwnerCEO() public onlyWhitelisted view returns(address) {
return ownerCEO;
}
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
function addAddressesToWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (addAddressToWhitelist(addrs[i])) {
success = true;
}
}
}
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
function removeAddressFromWhitelist(address addr) onlyOwner public returns(bool success) {
if (whitelist[addr]) {
whitelist[addr] = false;
emit WhitelistedAddressRemoved(addr);
success = true;
}
}
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
function removeAddressesFromWhitelist(address[] addrs) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addrs.length; i++) {
if (removeAddressFromWhitelist(addrs[i])) {
success = true;
}
}
}
}
| 6,426,859 | [
1,
18927,
225,
1021,
3497,
7523,
6835,
711,
279,
10734,
434,
6138,
16,
471,
8121,
5337,
6093,
3325,
4186,
18,
225,
1220,
9330,
5032,
326,
4471,
434,
315,
1355,
4371,
9654,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
3497,
7523,
353,
14223,
6914,
288,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
10734,
31,
203,
203,
565,
2874,
12,
11890,
225,
516,
1758,
13,
282,
10734,
1564,
31,
203,
565,
2254,
1071,
1056,
1887,
273,
374,
31,
203,
203,
565,
871,
3497,
7523,
329,
1887,
8602,
12,
2867,
3091,
1769,
203,
565,
871,
3497,
7523,
329,
1887,
10026,
12,
2867,
3091,
1769,
203,
7010,
565,
9606,
1338,
18927,
329,
1435,
288,
203,
3639,
2583,
12,
20409,
63,
3576,
18,
15330,
19226,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
1435,
1071,
288,
203,
5411,
10734,
63,
3576,
18,
15330,
65,
273,
638,
31,
21281,
5411,
10734,
63,
2211,
65,
273,
638,
31,
21281,
565,
289,
203,
203,
565,
445,
527,
1887,
774,
18927,
12,
2867,
3091,
13,
1338,
18927,
329,
1071,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
309,
16051,
20409,
63,
4793,
5717,
288,
203,
5411,
10734,
63,
4793,
65,
273,
638,
31,
203,
203,
5411,
1056,
1887,
273,
1056,
1887,
397,
404,
31,
203,
5411,
10734,
1564,
63,
1883,
1887,
65,
273,
3091,
31,
203,
203,
5411,
3626,
3497,
7523,
329,
1887,
8602,
12,
4793,
1769,
203,
5411,
2216,
273,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
527,
1887,
774,
18927,
12,
2867,
3091,
13,
1338,
18927,
329,
1071,
1135,
12,
6430,
2216,
13,
288,
203,
3639,
309,
16051,
20409,
63,
4793,
5717,
288,
203,
5411,
10734,
63,
4793,
65,
273,
638,
31,
203,
203,
5411,
1056,
1887,
273,
2
] |
pragma solidity 0.5.7;
contract RSADonations {
struct PublicKey { // Storage for RSA public key.
uint256 exponent;
uint256[] modulus; // big-endian representation of public-key modulus.
uint256 size; // Size of modulus in bits. Must be a multiple of 256.
}
mapping(bytes32 /* public key hash */ => PublicKey) public publicKeys;
mapping(bytes32 /* public key hash */ => uint256) public balances;
struct Donation {
uint256 amount; // Total donated to this key, from this address
uint256 recoveryDeadline; // Unix time when this donation is recoverable
uint256 lastUpdate; // Unix time of when this record was last updated
}
mapping(address /* donor */ =>
mapping(bytes32 /* public key hash */ => Donation)) public donations;
mapping(bytes32 /* public key hash */ =>
uint256 /* Unix time when funds last taken */) public lastClaims;
// Used in challenge message, to prevent replay attacks
mapping(bytes32 /* public key hash */ => uint256) public claimNonce;
event NewKeyRegistered(address sender, bytes32 publicKeyHash);
event DonationToKey(
address sender,
uint256 amount,
uint256 newBalance,
uint256 newSenderBalance, // Balance in donations[publicKeyHash][sender]
uint256 recoveryDeadline,
bytes32 publicKeyHash
);
event DonationRecovered( // Fired when donation is recovered by sender
address sender, bytes32 publicKeyHash, uint256 amount,
uint256 newBalance // balances[publicKeyHash]
);
event DonationClaimed( // Fired when donation is recovered by public key
address to,
address transmitter, // msg.sender for this tx
uint256 transmitterReward, // How much was sent to transmitter of tx.
uint256 amount // How much was sent to `to` address
);
event DonationBalanceReset( // Fired when donor balance reset to zero
address donor, bytes32 publicKeyHash);
event BadModulus(bytes32 publicKeyHash); // Fired when bitsize doesn't match
event DonationRecoveryTooSoon( // Fired on recovery before recoveryDeadline
address sender, bytes32 publicKeyHash, uint256 recoveryDeadline);
event DonationAlreadyClaimed( // Fired on recovery of donation already claimed
address sender, bytes32 publicKeyHash, uint256 lastClaim, uint256 recoveryTime);
event BadClaimSignature( // Fired when a claim has a bad signature
address sender, bytes32 publicKeyHash, bytes32 signatureHash);
address owner; // Owner of the contract
constructor() public { owner = msg.sender; }
function publicKeyHash(uint256[] memory _modulus, uint256 _exponent,
uint256 _size) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_modulus, _exponent, _size));
}
function donateToNewPublicKey(uint256 _recoveryDeadline,
uint256[] memory _keyModulus, uint256 _keyExponent, uint256 _keySize) public payable {
bytes32 keyHash = publicKeyHash(_keyModulus, _keyExponent, _keySize);
if (_keyModulus.length * 256 != _keySize) {
emit BadModulus(keyHash);
return;
}
publicKeys[keyHash].modulus = _keyModulus;
publicKeys[keyHash].exponent = _keyExponent;
publicKeys[keyHash].size = _keySize;
emit NewKeyRegistered(msg.sender, keyHash);
donateToKnownPublicKey(_recoveryDeadline, keyHash);
}
function max(uint256 a, uint256 b) public pure returns(uint256) {
return a > b ? a : b;
}
function donateToKnownPublicKey(uint256 _recoveryDeadline, bytes32 _keyHash)
public payable {
// Without this, the donation becomes unrecoverable.
require(lastClaims[_keyHash] < now, "Must make a donation at least 1s since last claim.");
Donation memory donation = donations[msg.sender][_keyHash];
donation.recoveryDeadline = max(donation.recoveryDeadline,
_recoveryDeadline); // Whichever is later
if (lastClaims[_keyHash] > donation.lastUpdate) {
donation.amount = msg.value;
emit DonationBalanceReset(msg.sender, _keyHash);
} else {
donation.amount += msg.value;
}
donation.lastUpdate = now;
donations[msg.sender][_keyHash] = donation; // Copy back to storage
balances[_keyHash] += msg.value;
emit DonationToKey(msg.sender, msg.value, balances[_keyHash], donation.amount,
_recoveryDeadline, _keyHash);
}
function recoverDonation(bytes32 _keyHash) public {
Donation memory donation = donations[msg.sender][_keyHash];
require(donation.amount > 0, "Can't recover trivial donation.");
if (donation.recoveryDeadline >= now) { // After the recovery deadline?
emit DonationRecoveryTooSoon(msg.sender, _keyHash, donation.recoveryDeadline);
return;
}
if (donation.lastUpdate <= lastClaims[_keyHash]) { // Not already claimed?
emit DonationAlreadyClaimed(msg.sender, _keyHash, lastClaims[_keyHash], now);
return;
}
delete donations[msg.sender][_keyHash];
emit DonationBalanceReset(msg.sender, _keyHash);
balances[_keyHash] -= donation.amount;
assert(balances[_keyHash] >= 0);
emit DonationRecovered(
msg.sender, _keyHash, donation.amount, balances[_keyHash]);
msg.sender.transfer(donation.amount);
}
function resetDonationDeadline(address _from, bytes32 _keyHash) public {
require(msg.sender == owner, "Only owner can reset deadlines");
donations[_from][_keyHash].recoveryDeadline = 0;
}
function claimDonation(bytes32 _keyHash, address payable _to,
uint256 _transmitterReward, uint256[] memory _signature) public {
uint256 balance = balances[_keyHash];
require(balance >= _transmitterReward, "Transmitter reward unpayable.");
if (!verify(_keyHash, _to, _transmitterReward, _signature)) {
emit BadClaimSignature(msg.sender, _keyHash,
keccak256(abi.encodePacked(_signature)));
return;
}
balances[_keyHash] = 0;
lastClaims[_keyHash] = now;
claimNonce[_keyHash] += 1;
emit DonationClaimed(_to, msg.sender, _transmitterReward, balance);
if (_transmitterReward > 0) { msg.sender.transfer(_transmitterReward); }
uint256 remainder = balance - _transmitterReward;
if (remainder > 0) { _to.transfer(remainder); }
}
function verify(bytes32 _keyHash, address payable _to, uint256 _transmitterReward,
uint256[] memory _signature) public view returns (bool) {
uint256[] memory challengeMessage = claimChallengeMessage(
_keyHash, _to, _transmitterReward);
uint256[] memory cipherText = encrypt(_keyHash, _signature);
if (cipherText.length != challengeMessage.length) { return false; }
for (uint256 i = 0; i < cipherText.length; i++) {
if (cipherText[i] != challengeMessage[i]) {
return false;
}
}
return true;
}
function claimChallengeMessage(
bytes32 _keyHash, address payable _to, uint256 _transmitterReward)
public view returns (uint256[] memory) {
PublicKey memory pk = publicKeys[_keyHash];
uint256[] memory rv = new uint256[](pk.modulus.length);
bytes32 initialHash = keccak256(abi.encodePacked(
claimNonce[_keyHash], _to, _transmitterReward, msg.sender));
for (uint256 i = 0; i < pk.modulus.length; i++) {
rv[i] = uint256(keccak256(abi.encodePacked(i, initialHash)));
}
if (rv[0] < pk.modulus[0]) { // Try to avoid expensive unnecessary bigmodexp
return rv;
}
return remainder(rv, pk.modulus);
}
uint256 constant WORD = 32; // Number of bytes in a 256-bit word
/* @dev NB: This is "text-book RSA" encryption, used here only for signature
* verification. Don't use this for serious encryption without random padding,
* etc.
*/
function encrypt(bytes32 _keyHash, uint256[] memory _message)
public view returns (uint256[] memory) {
PublicKey memory pk = publicKeys[_keyHash];
require(_message.length <= pk.modulus.length,
"Can't encrypt more information than the modulus.");
return bigModExp(_message, pk.exponent, pk.modulus);
}
function remainder(uint256[] memory _dividend, uint256[] memory _divisor)
public view returns(uint256[] memory) {
return bigModExp(_dividend, 1, _divisor);
}
function bigModExp(uint256[] memory _base, uint256 _exponent, uint256[] memory _modulus)
public view returns (uint256[] memory) {
uint256 inputSize = 3 + _modulus.length + 1 + _base.length;
uint256[] memory input = new uint256[](inputSize);
uint256 cursor = 0;
// We're operating in words, here, but the bigmodexp API expects bytes.
input[cursor++] = _base.length * WORD;
input[cursor++] = WORD;
input[cursor++] = _modulus.length * WORD;
for (uint256 i = 0; i < _base.length; i++) {
input[cursor++] = _base[i];
}
input[cursor++] = _exponent;
for (uint256 i = 0; i < _modulus.length; i++) {
input[cursor++] = _modulus[i];
}
assert(cursor == inputSize);
uint256 success;
uint256 outputLength = _modulus.length; // Can't use attributes in assembly
uint256[] memory output = new uint256[](2*outputLength); // XXX: Avoid memory corruption??
uint256 word = WORD; // Can't use constants in assembly
assembly {
success := staticcall(
not(0), // Allow arbitrary gas. XXX get this more precise
0x05, // The bigmodexp precompiled contract address
// address of inputs is one word past the length value
// https://solidity.readthedocs.io/en/v0.4.24/miscellaneous.html#layout-of-state-variables-in-storage
add(input, word),
mul(inputSize, word), // Size of input, in bytes
add(output, word), // Same logic as for input
mul(outputLength, word)) // Size of output, in bytes
}
require(success != 0, "bigModExp call failed.");
uint256[] memory actualOutput = new uint256[](outputLength);
for (uint256 i = 0; i < outputLength; i++) {
actualOutput[i] = output[i];
}
return actualOutput;
}
}
| Can't use constants in assembly
| uint256 word = WORD; | 5,403,149 | [
1,
2568,
1404,
999,
6810,
316,
19931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
2076,
273,
21464,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/IStaking.sol
/*
Staking interface
EIP-900 staking interface
https://github.com/gysr-io/core
h/t https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
pragma solidity ^0.6.12;
interface IStaking {
// events
event Staked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 total,
bytes data
);
/**
* @notice stakes a certain amount of tokens, transferring this amount from
the user to the contract
* @param amount number of tokens to stake
*/
function stake(uint256 amount, bytes calldata) external;
/**
* @notice stakes a certain amount of tokens for an address, transfering this
amount from the caller to the contract, on behalf of the specified address
* @param user beneficiary address
* @param amount number of tokens to stake
*/
function stakeFor(
address user,
uint256 amount,
bytes calldata
) external;
/**
* @notice unstakes a certain amount of tokens, returning these tokens
to the user
* @param amount number of tokens to unstake
*/
function unstake(uint256 amount, bytes calldata) external;
/**
* @param addr the address of interest
* @return the current total of tokens staked for an address
*/
function totalStakedFor(address addr) external view returns (uint256);
/**
* @return the current total amount of tokens staked by all users
*/
function totalStaked() external view returns (uint256);
/**
* @return the staking token for this staking contract
*/
function token() external view returns (address);
/**
* @return true if the staking contract support history
*/
function supportsHistory() external pure returns (bool);
}
// File: contracts/IGeyser.sol
/*
Geyser interface
This defines the core Geyser contract interface as an extension to the
standard IStaking interface
https://github.com/gysr-io/core
*/
pragma solidity ^0.6.12;
/**
* @title Geyser interface
*/
abstract contract IGeyser is IStaking, Ownable {
// events
event RewardsDistributed(address indexed user, uint256 amount);
event RewardsFunded(
uint256 amount,
uint256 duration,
uint256 start,
uint256 total
);
event RewardsUnlocked(uint256 amount, uint256 total);
event RewardsExpired(uint256 amount, uint256 duration, uint256 start);
event GysrSpent(address indexed user, uint256 amount);
event GysrWithdrawn(uint256 amount);
// IStaking
/**
* @notice no support for history
* @return false
*/
function supportsHistory() external override pure returns (bool) {
return false;
}
// IGeyser
/**
* @return staking token for this Geyser
*/
function stakingToken() external virtual view returns (address);
/**
* @return reward token for this Geyser
*/
function rewardToken() external virtual view returns (address);
/**
* @notice fund Geyser by locking up reward tokens for distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
*/
function fund(uint256 amount, uint256 duration) external virtual;
/**
* @notice fund Geyser by locking up reward tokens for future distribution
* @param amount number of reward tokens to lock up as funding
* @param duration period (seconds) over which funding will be unlocked
* @param start time (seconds) at which funding begins to unlock
*/
function fund(
uint256 amount,
uint256 duration,
uint256 start
) external virtual;
/**
* @notice withdraw GYSR tokens applied during unstaking
* @param amount number of GYSR to withdraw
*/
function withdraw(uint256 amount) external virtual;
/**
* @notice unstake while applying GYSR token for boosted rewards
* @param amount number of tokens to unstake
* @param gysr number of GYSR tokens to apply for boost
*/
function unstake(
uint256 amount,
uint256 gysr,
bytes calldata
) external virtual;
/**
* @notice update accounting, unlock tokens, etc.
*/
function update() external virtual;
/**
* @notice clean geyser, expire old fundings, etc.
*/
function clean() external virtual;
}
// File: contracts/GeyserPool.sol
/*
Geyser token pool
Simple contract to implement token pool of arbitrary ERC20 token.
This is owned and used by a parent Geyser
https://github.com/gysr-io/core
h/t https://github.com/ampleforth/token-geyser
*/
pragma solidity ^0.6.12;
contract GeyserPool is Ownable {
using SafeERC20 for IERC20;
IERC20 public token;
constructor(address token_) public {
token = IERC20(token_);
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner {
token.safeTransfer(to, value);
}
}
// File: contracts/MathUtils.sol
/*
Math utilities
This library implements various logarithmic math utilies which support
other contracts and specifically the GYSR multiplier calculation
https://github.com/gysr-io/core
h/t https://github.com/abdk-consulting/abdk-libraries-solidity
*/
pragma solidity ^0.6.12;
library MathUtils {
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function logbase2(int128 x) internal pure returns (int128) {
require(x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) {
xc >>= 64;
msb += 64;
}
if (xc >= 0x100000000) {
xc >>= 32;
msb += 32;
}
if (xc >= 0x10000) {
xc >>= 16;
msb += 16;
}
if (xc >= 0x100) {
xc >>= 8;
msb += 8;
}
if (xc >= 0x10) {
xc >>= 4;
msb += 4;
}
if (xc >= 0x4) {
xc >>= 2;
msb += 2;
}
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = (msb - 64) << 64;
uint256 ux = uint256(x) << (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256(b);
}
return int128(result);
}
/**
* @notice calculate natural logarithm of x
* @dev magic constant comes from ln(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function ln(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
(uint256(logbase2(x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF) >>
128
);
}
/**
* @notice calculate logarithm base 10 of x
* @dev magic constant comes from log10(2) * 2^128 -> hex
* @param x signed 64.64-bit fixed point number, require x > 0
* @return signed 64.64-bit fixed point number
*/
function logbase10(int128 x) internal pure returns (int128) {
require(x > 0);
return
int128(
(uint256(logbase2(x)) * 0x4d104d427de7fce20a6e420e02236748) >>
128
);
}
// wrapper functions to allow testing
function testlogbase2(int128 x) public pure returns (int128) {
return logbase2(x);
}
function testlogbase10(int128 x) public pure returns (int128) {
return logbase10(x);
}
}
// File: contracts/Geyser.sol
/*
Geyser
This implements the core Geyser contract, which allows for generalized
staking, yield farming, and token distribution. This also implements
the GYSR spending mechanic for boosted reward distribution.
https://github.com/gysr-io/core
h/t https://github.com/ampleforth/token-geyser
*/
pragma solidity ^0.6.12;
/**
* @title Geyser
*/
contract Geyser is IGeyser, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using MathUtils for int128;
// single stake by user
struct Stake {
uint256 shares;
uint256 timestamp;
}
// summary of total user stake/shares
struct User {
uint256 shares;
uint256 shareSeconds;
uint256 lastUpdated;
}
// single funding/reward schedule
struct Funding {
uint256 amount;
uint256 shares;
uint256 unlocked;
uint256 lastUpdated;
uint256 start;
uint256 end;
uint256 duration;
}
// constants
uint256 public constant BONUS_DECIMALS = 18;
uint256 public constant INITIAL_SHARES_PER_TOKEN = 10**6;
uint256 public constant MAX_ACTIVE_FUNDINGS = 16;
// token pool fields
GeyserPool private immutable _stakingPool;
GeyserPool private immutable _unlockedPool;
GeyserPool private immutable _lockedPool;
Funding[] public fundings;
// user staking fields
mapping(address => User) public userTotals;
mapping(address => Stake[]) public userStakes;
// time bonus fields
uint256 public immutable bonusMin;
uint256 public immutable bonusMax;
uint256 public immutable bonusPeriod;
// global state fields
uint256 public totalLockedShares;
uint256 public totalStakingShares;
uint256 public totalRewards;
uint256 public totalGysrRewards;
uint256 public totalStakingShareSeconds;
uint256 public lastUpdated;
// gysr fields
IERC20 private immutable _gysr;
/**
* @param stakingToken_ the token that will be staked
* @param rewardToken_ the token distributed to users as they unstake
* @param bonusMin_ initial time bonus
* @param bonusMax_ maximum time bonus
* @param bonusPeriod_ period (in seconds) over which time bonus grows to max
* @param gysr_ address for GYSR token
*/
constructor(
address stakingToken_,
address rewardToken_,
uint256 bonusMin_,
uint256 bonusMax_,
uint256 bonusPeriod_,
address gysr_
) public {
require(
bonusMin_ <= bonusMax_,
"Geyser: initial time bonus greater than max"
);
_stakingPool = new GeyserPool(stakingToken_);
_unlockedPool = new GeyserPool(rewardToken_);
_lockedPool = new GeyserPool(rewardToken_);
bonusMin = bonusMin_;
bonusMax = bonusMax_;
bonusPeriod = bonusPeriod_;
_gysr = IERC20(gysr_);
lastUpdated = block.timestamp;
}
// IStaking
/**
* @inheritdoc IStaking
*/
function stake(uint256 amount, bytes calldata) external override {
_stake(msg.sender, msg.sender, amount);
}
/**
* @inheritdoc IStaking
*/
function stakeFor(
address user,
uint256 amount,
bytes calldata
) external override {
_stake(msg.sender, user, amount);
}
/**
* @inheritdoc IStaking
*/
function unstake(uint256 amount, bytes calldata) external override {
_unstake(amount, 0);
}
/**
* @inheritdoc IStaking
*/
function totalStakedFor(address addr)
public
override
view
returns (uint256)
{
if (totalStakingShares == 0) {
return 0;
}
return
totalStaked().mul(userTotals[addr].shares).div(totalStakingShares);
}
/**
* @inheritdoc IStaking
*/
function totalStaked() public override view returns (uint256) {
return _stakingPool.balance();
}
/**
* @inheritdoc IStaking
* @dev redundant with stakingToken() in order to implement IStaking (EIP-900)
*/
function token() external override view returns (address) {
return address(_stakingPool.token());
}
// IGeyser
/**
* @inheritdoc IGeyser
*/
function stakingToken() public override view returns (address) {
return address(_stakingPool.token());
}
/**
* @inheritdoc IGeyser
*/
function rewardToken() public override view returns (address) {
return address(_unlockedPool.token());
}
/**
* @inheritdoc IGeyser
*/
function fund(uint256 amount, uint256 duration) public override {
fund(amount, duration, block.timestamp);
}
/**
* @inheritdoc IGeyser
*/
function fund(
uint256 amount,
uint256 duration,
uint256 start
) public override onlyOwner {
// validate
require(amount > 0, "Geyser: funding amount is zero");
require(start >= block.timestamp, "Geyser: funding start is past");
require(
fundings.length < MAX_ACTIVE_FUNDINGS,
"Geyser: exceeds max active funding schedules"
);
// update bookkeeping
_update(msg.sender);
// mint shares at current rate
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(INITIAL_SHARES_PER_TOKEN);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
// create new funding
fundings.push(
Funding({
amount: amount,
shares: mintedLockedShares,
unlocked: 0,
lastUpdated: start,
start: start,
end: start.add(duration),
duration: duration
})
);
// do transfer of funding
_lockedPool.token().safeTransferFrom(
msg.sender,
address(_lockedPool),
amount
);
emit RewardsFunded(amount, duration, start, totalLocked());
}
/**
* @inheritdoc IGeyser
*/
function withdraw(uint256 amount) external override onlyOwner {
require(amount > 0, "Geyser: withdraw amount is zero");
require(
amount <= _gysr.balanceOf(address(this)),
"Geyser: withdraw amount exceeds balance"
);
// do transfer
_gysr.safeTransfer(msg.sender, amount);
emit GysrWithdrawn(amount);
}
/**
* @inheritdoc IGeyser
*/
function unstake(
uint256 amount,
uint256 gysr,
bytes calldata
) external override {
_unstake(amount, gysr);
}
/**
* @inheritdoc IGeyser
*/
function update() external override nonReentrant {
_update(msg.sender);
}
/**
* @inheritdoc IGeyser
*/
function clean() external override onlyOwner {
// update bookkeeping
_update(msg.sender);
// check for stale funding schedules to expire
uint256 removed = 0;
uint256 originalSize = fundings.length;
for (uint256 i = 0; i < originalSize; i++) {
Funding storage funding = fundings[i.sub(removed)];
uint256 idx = i.sub(removed);
if (_unlockable(idx) == 0 && block.timestamp >= funding.end) {
emit RewardsExpired(
funding.amount,
funding.duration,
funding.start
);
// remove at idx by copying last element here, then popping off last
// (we don't care about order)
fundings[idx] = fundings[fundings.length.sub(1)];
fundings.pop();
removed = removed.add(1);
}
}
}
// Geyser
/**
* @dev internal implementation of staking methods
* @param staker address to do deposit of staking tokens
* @param beneficiary address to gain credit for this stake operation
* @param amount number of staking tokens to deposit
*/
function _stake(
address staker,
address beneficiary,
uint256 amount
) private nonReentrant {
// validate
require(amount > 0, "Geyser: stake amount is zero");
require(
beneficiary != address(0),
"Geyser: beneficiary is zero address"
);
// mint staking shares at current rate
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(INITIAL_SHARES_PER_TOKEN);
require(mintedStakingShares > 0, "Geyser: stake amount too small");
// update bookkeeping
_update(beneficiary);
// update user staking info
User storage user = userTotals[beneficiary];
user.shares = user.shares.add(mintedStakingShares);
user.lastUpdated = block.timestamp;
userStakes[beneficiary].push(
Stake(mintedStakingShares, block.timestamp)
);
// add newly minted shares to global total
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// transactions
_stakingPool.token().safeTransferFrom(
staker,
address(_stakingPool),
amount
);
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev internal implementation of unstaking methods
* @param amount number of tokens to unstake
* @param gysr number of GYSR tokens applied to unstaking operation
* @return number of reward tokens distributed
*/
function _unstake(uint256 amount, uint256 gysr)
private
nonReentrant
returns (uint256)
{
// validate
require(amount > 0, "Geyser: unstake amount is zero");
require(
totalStakedFor(msg.sender) >= amount,
"Geyser: unstake amount exceeds balance"
);
// update bookkeeping
_update(msg.sender);
// do unstaking, first-in last-out, respecting time bonus
uint256 timeWeightedShareSeconds = _unstakeFirstInLastOut(amount);
// compute and apply GYSR token bonus
uint256 gysrWeightedShareSeconds = gysrBonus(gysr)
.mul(timeWeightedShareSeconds)
.div(10**BONUS_DECIMALS);
uint256 rewardAmount = totalUnlocked()
.mul(gysrWeightedShareSeconds)
.div(totalStakingShareSeconds.add(gysrWeightedShareSeconds));
// update global stats for distributions
if (gysr > 0) {
totalGysrRewards = totalGysrRewards.add(rewardAmount);
}
totalRewards = totalRewards.add(rewardAmount);
// transactions
_stakingPool.transfer(msg.sender, amount);
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
if (rewardAmount > 0) {
_unlockedPool.transfer(msg.sender, rewardAmount);
emit RewardsDistributed(msg.sender, rewardAmount);
}
if (gysr > 0) {
_gysr.safeTransferFrom(msg.sender, address(this), gysr);
emit GysrSpent(msg.sender, gysr);
}
return rewardAmount;
}
/**
* @dev helper function to actually execute unstaking, first-in last-out,
while computing and applying time bonus. This function also updates
user and global totals for shares and share-seconds.
* @param amount number of staking tokens to withdraw
* @return time bonus weighted staking share seconds
*/
function _unstakeFirstInLastOut(uint256 amount) private returns (uint256) {
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(
totalStaked()
);
require(stakingSharesToBurn > 0, "Geyser: unstake amount too small");
// redeem from most recent stake and go backwards in time.
uint256 shareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 bonusWeightedShareSeconds = 0;
Stake[] storage stakes = userStakes[msg.sender];
while (sharesLeftToBurn > 0) {
Stake storage lastStake = stakes[stakes.length - 1];
uint256 stakeTime = block.timestamp.sub(lastStake.timestamp);
uint256 bonus = timeBonus(stakeTime);
if (lastStake.shares <= sharesLeftToBurn) {
// fully redeem a past stake
bonusWeightedShareSeconds = bonusWeightedShareSeconds.add(
lastStake.shares.mul(stakeTime).mul(bonus).div(
10**BONUS_DECIMALS
)
);
shareSecondsToBurn = shareSecondsToBurn.add(
lastStake.shares.mul(stakeTime)
);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.shares);
stakes.pop();
} else {
// partially redeem a past stake
bonusWeightedShareSeconds = bonusWeightedShareSeconds.add(
sharesLeftToBurn.mul(stakeTime).mul(bonus).div(
10**BONUS_DECIMALS
)
);
shareSecondsToBurn = shareSecondsToBurn.add(
sharesLeftToBurn.mul(stakeTime)
);
lastStake.shares = lastStake.shares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
// update user totals
User storage user = userTotals[msg.sender];
user.shareSeconds = user.shareSeconds.sub(shareSecondsToBurn);
user.shares = user.shares.sub(stakingSharesToBurn);
user.lastUpdated = block.timestamp;
// update global totals
totalStakingShareSeconds = totalStakingShareSeconds.sub(
shareSecondsToBurn
);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
return bonusWeightedShareSeconds;
}
/**
* @dev internal implementation of update method
* @param addr address for user accounting update
*/
function _update(address addr) private {
_unlockTokens();
// global accounting
uint256 deltaTotalShareSeconds = (block.timestamp.sub(lastUpdated)).mul(
totalStakingShares
);
totalStakingShareSeconds = totalStakingShareSeconds.add(
deltaTotalShareSeconds
);
lastUpdated = block.timestamp;
// user accounting
User storage user = userTotals[addr];
uint256 deltaUserShareSeconds = (block.timestamp.sub(user.lastUpdated))
.mul(user.shares);
user.shareSeconds = user.shareSeconds.add(deltaUserShareSeconds);
user.lastUpdated = block.timestamp;
}
/**
* @dev unlocks reward tokens based on funding schedules
*/
function _unlockTokens() private {
uint256 tokensToUnlock = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
// handle any leftover
tokensToUnlock = lockedTokens;
} else {
// normal case: unlock some shares from each funding schedule
uint256 sharesToUnlock = 0;
for (uint256 i = 0; i < fundings.length; i++) {
uint256 shares = _unlockable(i);
Funding storage funding = fundings[i];
if (shares > 0) {
funding.unlocked = funding.unlocked.add(shares);
funding.lastUpdated = block.timestamp;
sharesToUnlock = sharesToUnlock.add(shares);
}
}
tokensToUnlock = sharesToUnlock.mul(lockedTokens).div(
totalLockedShares
);
totalLockedShares = totalLockedShares.sub(sharesToUnlock);
}
if (tokensToUnlock > 0) {
_lockedPool.transfer(address(_unlockedPool), tokensToUnlock);
emit RewardsUnlocked(tokensToUnlock, totalUnlocked());
}
}
/**
* @dev helper function to compute updates to funding schedules
* @param idx index of the funding
* @return the number of unlockable shares
*/
function _unlockable(uint256 idx) private view returns (uint256) {
Funding storage funding = fundings[idx];
// funding schedule is in future
if (block.timestamp < funding.start) {
return 0;
}
// empty
if (funding.unlocked >= funding.shares) {
return 0;
}
// handle zero-duration period or leftover dust from integer division
if (block.timestamp >= funding.end) {
return funding.shares.sub(funding.unlocked);
}
return
(block.timestamp.sub(funding.lastUpdated)).mul(funding.shares).div(
funding.duration
);
}
/**
* @notice compute time bonus earned as a function of staking time
* @param time length of time for which the tokens have been staked
* @return bonus multiplier for time
*/
function timeBonus(uint256 time) public view returns (uint256) {
if (time >= bonusPeriod) {
return uint256(10**BONUS_DECIMALS).add(bonusMax);
}
// linearly interpolate between bonus min and bonus max
uint256 bonus = bonusMin.add(
(bonusMax.sub(bonusMin)).mul(time).div(bonusPeriod)
);
return uint256(10**BONUS_DECIMALS).add(bonus);
}
/**
* @notice compute GYSR bonus as a function of usage ratio and GYSR spent
* @param gysr number of GYSR token applied to bonus
* @return multiplier value
*/
function gysrBonus(uint256 gysr) public view returns (uint256) {
if (gysr == 0) {
return 10**BONUS_DECIMALS;
}
require(
gysr >= 10**BONUS_DECIMALS,
"Geyser: GYSR amount is between 0 and 1"
);
uint256 buffer = uint256(10**(BONUS_DECIMALS - 2)); // 0.01
uint256 r = ratio().add(buffer);
uint256 x = gysr.add(buffer);
return
uint256(10**BONUS_DECIMALS).add(
uint256(int128(x.mul(2**64).div(r)).logbase10())
.mul(10**BONUS_DECIMALS)
.div(2**64)
);
}
/**
* @return portion of rewards which have been boosted by GYSR token
*/
function ratio() public view returns (uint256) {
if (totalRewards == 0) {
return 0;
}
return totalGysrRewards.mul(10**BONUS_DECIMALS).div(totalRewards);
}
// Geyser -- informational functions
/**
* @return total number of locked reward tokens
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return total number of unlocked reward tokens
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return number of active funding schedules
*/
function fundingCount() public view returns (uint256) {
return fundings.length;
}
/**
* @param addr address of interest
* @return number of active stakes for user
*/
function stakeCount(address addr) public view returns (uint256) {
return userStakes[addr].length;
}
/**
* @notice preview estimated reward distribution for full unstake with no GYSR applied
* @return estimated reward
* @return estimated overall multiplier
* @return estimated raw user share seconds that would be burned
* @return estimated total unlocked rewards
*/
function preview()
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return preview(msg.sender, totalStakedFor(msg.sender), 0);
}
/**
* @notice preview estimated reward distribution for unstaking
* @param addr address of interest for preview
* @param amount number of tokens that would be unstaked
* @param gysr number of GYSR tokens that would be applied
* @return estimated reward
* @return estimated overall multiplier
* @return estimated raw user share seconds that would be burned
* @return estimated total unlocked rewards
*/
function preview(
address addr,
uint256 amount,
uint256 gysr
)
public
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
// compute expected updates to global totals
uint256 deltaUnlocked = 0;
if (totalLockedShares != 0) {
uint256 sharesToUnlock = 0;
for (uint256 i = 0; i < fundings.length; i++) {
sharesToUnlock = sharesToUnlock.add(_unlockable(i));
}
deltaUnlocked = sharesToUnlock.mul(totalLocked()).div(
totalLockedShares
);
}
// no need for unstaking/rewards computation
if (amount == 0) {
return (0, 0, 0, totalUnlocked().add(deltaUnlocked));
}
// check unstake amount
require(
amount <= totalStakedFor(addr),
"Geyser: preview amount exceeds balance"
);
// compute unstake amount in shares
uint256 shares = totalStakingShares.mul(amount).div(totalStaked());
require(shares > 0, "Geyser: preview amount too small");
uint256 rawShareSeconds = 0;
uint256 timeBonusShareSeconds = 0;
// compute first-in-last-out, time bonus weighted, share seconds
uint256 i = userStakes[addr].length.sub(1);
while (shares > 0) {
Stake storage s = userStakes[addr][i];
uint256 time = block.timestamp.sub(s.timestamp);
if (s.shares < shares) {
rawShareSeconds = rawShareSeconds.add(s.shares.mul(time));
timeBonusShareSeconds = timeBonusShareSeconds.add(
s.shares.mul(time).mul(timeBonus(time)).div(
10**BONUS_DECIMALS
)
);
shares = shares.sub(s.shares);
} else {
rawShareSeconds = rawShareSeconds.add(shares.mul(time));
timeBonusShareSeconds = timeBonusShareSeconds.add(
shares.mul(time).mul(timeBonus(time)).div(
10**BONUS_DECIMALS
)
);
break;
}
// this will throw on underflow
i = i.sub(1);
}
// apply gysr bonus
uint256 gysrBonusShareSeconds = gysrBonus(gysr)
.mul(timeBonusShareSeconds)
.div(10**BONUS_DECIMALS);
// compute rewards based on expected updates
uint256 expectedTotalShareSeconds = totalStakingShareSeconds
.add((block.timestamp.sub(lastUpdated)).mul(totalStakingShares))
.add(gysrBonusShareSeconds)
.sub(rawShareSeconds);
uint256 reward = (totalUnlocked().add(deltaUnlocked))
.mul(gysrBonusShareSeconds)
.div(expectedTotalShareSeconds);
// compute effective bonus
uint256 bonus = uint256(10**BONUS_DECIMALS)
.mul(gysrBonusShareSeconds)
.div(rawShareSeconds);
return (
reward,
bonus,
rawShareSeconds,
totalUnlocked().add(deltaUnlocked)
);
}
} | * @inheritdoc IGeyser/ | function update() external override nonReentrant {
_update(msg.sender);
}
| 303,602 | [
1,
36,
10093,
13102,
402,
550,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
1435,
3903,
3849,
1661,
426,
8230,
970,
288,
203,
3639,
389,
2725,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract dbond {
address owner;
struct blockinfo {
uint256 outstanding; // remaining debt at block
uint256 dividend; // % dividend users can claim
uint256 value; // actual ether value at block
uint256 index; // used in frontend for async checks
}
struct debtinfo {
uint256 idx; // dividend array position
uint256 pending; // pending balance at block
uint256 initial; // initial ammount for stats
}
struct account {
uint256 ebalance; // ether balance
mapping(uint256 => debtinfo) owed; // keeps track of outstanding debt
}
uint256 public bondsize; // size of the current bond
uint256 public interest; // interest to pay clients expressed in ETH(ie: 10% is 10ETH)
uint256 public IDX; // current dividend block
mapping(uint256 => blockinfo) public blockData; // dividend block data
mapping(address => account) public balances; // public user balances
bool public selling; // are we selling bonds?
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "only owner can call.");
_;
}
modifier canBuy() {
require(selling, "bonds are not selling");
if(bondsize > 0)
require(msg.value <= bondsize-blockData[IDX].value, "larger than bond");
_;
}
// sets the maximum ammount to receive
// cannot be lowered unless this bond sale is closed(prevents overflows)
function setBondSize(uint256 _bondsize) public onlyOwner {
require(_bondsize >= bondsize, "for a reduced bond size please end the current sale and make a new one");
bondsize = _bondsize;
}
// Sets the interest rate for all future purchases
// current outstanding debt is not affected by this
function setInterestRate(uint256 _interest) public onlyOwner {
interest = _interest;
}
// enables a bond sale
// if the bondsize is set to 0, the sale becomes akin to a continous bond contract
function sellBond(uint256 _bondsize, uint256 _interest) public onlyOwner {
selling = true;
bondsize = _bondsize;
interest = _interest;
}
// terminates a bond sale, the outstanding still needs to be paid off
function endBondSale() public onlyOwner {
selling = false;
blockData[IDX].dividend = 0;
_nextblock();
}
// makes a payment to all outstanding debt at block IDX
// advances the bond block by 1 and distributes in terms of percentage
function payBond() public payable onlyOwner {
// keeps track of the actual outstanding, prevents ether leaking
require(msg.value > 0, "zero payment detected");
require(msg.value <= blockData[IDX].outstanding, "overpayment will result in lost Ether");
// actual payment % that goes to all buyers
blockData[IDX].dividend = (msg.value * 100 ether) / blockData[IDX].outstanding;
_nextblock();
blockData[IDX].outstanding -= (blockData[IDX-1].outstanding * blockData[IDX-1].dividend ) / 100 ether;
}
function buyBond() public payable canBuy {
_bond(msg.sender, msg.value);
}
// withdraws ether to the user account
// user has to claim his money by calling getOwed first
function withdraw() public {
require(balances[msg.sender].ebalance > 0, "not enough to withdraw");
uint256 sval = balances[msg.sender].ebalance;
balances[msg.sender].ebalance = 0;
msg.sender.transfer(sval);
emit event_withdraw(msg.sender, sval);
}
// returns the ammount that is owed to that user at a specific block
function owedAt(uint256 blk) public view returns(uint256, uint256, uint256) {
return (balances[msg.sender].owed[blk].idx,
balances[msg.sender].owed[blk].pending,
balances[msg.sender].owed[blk].initial );
}
// actual buy calculation, adds to the outstanding debt
// interest is calculated and added here according to the current rate
function _bond(address addr, uint256 val) internal {
uint256 tval = val + ((val * interest) / 100 ether);
balances[owner].ebalance += val;
blockData[IDX].value += val;
blockData[IDX].outstanding += tval;
balances[addr].owed[IDX].idx = IDX;
balances[addr].owed[IDX].pending += tval;
balances[addr].owed[IDX].initial += tval;
emit event_buy(val);
}
// moves the bond block forward by 1, carries over all previous debt
function _nextblock() internal {
IDX += 1;
blockData[IDX].index = IDX;
// previous debt rolls over to next block
blockData[IDX].outstanding = blockData[IDX-1].outstanding;
emit event_newblk(IDX);
}
// users call this per bond they have purchased in order to claim their money
// their total owed for the bond goes down and is added to their ebalance
function getOwed(uint256 blk) public {
require(balances[msg.sender].owed[blk].idx < IDX && blk < IDX, "current block");
uint256 cdiv = 0;
for(uint256 i = 0; i < 1000; i++) {
cdiv = (balances[msg.sender].owed[blk].pending *
blockData[balances[msg.sender].owed[blk].idx].dividend ) / 100 ether;
cdiv = (cdiv > balances[msg.sender].owed[blk].pending)?
balances[msg.sender].owed[blk].pending : cdiv;
balances[msg.sender].owed[blk].idx += 1;
balances[msg.sender].owed[blk].pending -= cdiv;
balances[msg.sender].ebalance += cdiv;
if( balances[msg.sender].owed[blk].pending == 0 ||
balances[msg.sender].owed[blk].idx >= IDX )
return;
}
}
// events ------------------------------------------------------------------
event event_withdraw(address addr, uint256 val);
event event_newblk(uint256 idx);
event event_buy(uint256 val);
}
| sets the maximum ammount to receive cannot be lowered unless this bond sale is closed(prevents overflows) | function setBondSize(uint256 _bondsize) public onlyOwner {
require(_bondsize >= bondsize, "for a reduced bond size please end the current sale and make a new one");
bondsize = _bondsize;
}
| 1,764,416 | [
1,
4424,
326,
4207,
2125,
4778,
358,
6798,
2780,
506,
2612,
329,
3308,
333,
8427,
272,
5349,
353,
4375,
12,
29150,
87,
9391,
87,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
915,
444,
9807,
1225,
12,
11890,
5034,
389,
26425,
1467,
13,
1071,
1338,
5541,
288,
203,
202,
202,
6528,
24899,
26425,
1467,
1545,
8427,
1467,
16,
315,
1884,
279,
13162,
8427,
963,
9582,
679,
326,
783,
272,
5349,
471,
1221,
279,
394,
1245,
8863,
203,
202,
202,
26425,
1467,
273,
389,
26425,
1467,
31,
203,
202,
97,
203,
202,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract IHoneyBee {
/** ERC-721 INTERFACE */
function ownerOf(uint256 tokenId) public view virtual returns (address) {}
/** CUSTOM INTERFACE */
function nextTokenId() public returns(uint256) {}
function mintTo(uint256 amount, address _to) external {}
function burn(uint256 tokenId) external {}
}
contract HoneyBeeCustomPreSale is Ownable {
using SafeMath for uint256;
/** ADDRESSES */
address public ERC721TokenAddress;
address public preSaleAddress;
/** CONTRACTS */
IHoneyBee public nft;
/** MINT OPTIONS */
uint256 constant public MINT_PRICE = 0.1 ether;
uint256 public minted = 0;
/** SCHEDULING */
uint256 public preSaleOpen = 1639778400;//1639778400;
uint256 public preSaleDuration = 3600 * 24;//3600 * 24;
/** MERKLE */
bytes32 public customLimitMerkleRoot = "";
/** MAPPINGS */
mapping(address => uint256) public mintsPerAddress;
/** MODIFIERS */
modifier whenPreStarted() {
require(block.timestamp >= preSaleOpen, "PRE-SALE HASN'T OPENED YET");
require(block.timestamp <= preSaleOpen.add(preSaleDuration), "PRE-SALE IS CLOSED");
_;
}
/** EVENTS */
event ReceivedEther(address sender, uint256 amount);
constructor(
address _ERC721TokenAddress,
address _preSaleAddress
) Ownable() {
ERC721TokenAddress = _ERC721TokenAddress;
nft = IHoneyBee(_ERC721TokenAddress);
preSaleAddress = _preSaleAddress;
}
function setSaleStart(uint256 timestamp) external onlyOwner {
preSaleOpen = timestamp;
}
function setSaleDuration(uint256 timestamp) external onlyOwner {
preSaleDuration = timestamp;
}
function setCustomPreMintMerkleRoot(bytes32 _root) external onlyOwner {
customLimitMerkleRoot = _root;
}
function setPreSaleAddress(address _new) external onlyOwner {
preSaleAddress = _new;
}
function setNFT(address _nft) external onlyOwner {
nft = IHoneyBee(_nft);
}
/**
* @dev override msgSender to allow for meta transactions on OpenSea.
*/
function _msgSender()
override
internal
view
returns (address sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
function preSaleMintCustomLimit(uint256 amount, bytes32[] calldata proof) external payable whenPreStarted {
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, amount));
require(MerkleProof.verify(proof, customLimitMerkleRoot, leaf), "INVALID PROOF");
require(mintsPerAddress[_msgSender()] == 0, "ALREADY MINTED");
require(msg.value == MINT_PRICE.mul(amount), "ETHER SENT NOT CORRECT");
mintsPerAddress[_msgSender()] = mintsPerAddress[_msgSender()].add(amount);
minted = minted.add(amount);
nft.mintTo(amount, _msgSender());
payable(preSaleAddress).transfer(address(this).balance);
}
/**
* @dev Fallback function for receiving Ether
*/
receive() external payable {
emit ReceivedEther(msg.sender, msg.value);
}
function withdraw() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
} | * ERC-721 INTERFACE */ | function ownerOf(uint256 tokenId) public view virtual returns (address) {}
| 115,258 | [
1,
654,
39,
17,
27,
5340,
11391,
11300,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
1135,
261,
2867,
13,
2618,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// 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 len insufficient");
return string(buffer);
}
}
/**
* @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;
}
}
}
/**
* @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);
}
}
}
}
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
library LibRoyaltiesV2 {
/*
* bytes4(keccak256('getRaribleV2Royalties(uint256)')) == 0xcad96cca
*/
bytes4 constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
}
interface RoyaltiesV2 {
event RoyaltiesSet(uint256 tokenId, LibPart.Part[] royalties);
function getRaribleV2Royalties(uint256 id) external view returns (LibPart.Part[] memory);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev 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;
}
}
/**
* @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()); // paused
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused()); // 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());
}
}
/**
* @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;
}
}
/**
* @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()); // wrong 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)); // own=0x0
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
abstract contract AbstractRoyalties {
mapping (uint256 => LibPart.Part[]) internal royalties;
function _saveRoyalties(uint256 id, LibPart.Part[] memory _royalties) internal {
uint256 totalValue;
for (uint i = 0; i < _royalties.length; i++) {
require(_royalties[i].account != address(0x0)); // Not present
require(_royalties[i].value != 0); // Non positive
totalValue += _royalties[i].value;
royalties[id].push(_royalties[i]);
}
require(totalValue < 10000); // Should be < 10000
_onRoyaltiesSet(id, _royalties);
}
function _updateAccount(uint256 _id, address _from, address _to) internal {
uint length = royalties[_id].length;
for(uint i = 0; i < length; i++) {
if (royalties[_id][i].account == _from) {
royalties[_id][i].account = payable(address(uint160(_to)));
}
}
}
function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) virtual internal;
}
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited); // Already inited
_;
inited = true;
}
}
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(verify(userAddress, metaTx, sigR, sigS, sigV)); // signature do not match"
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success); // should be successful
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0)); // INVALID_SIGNER
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
/**
* @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: 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: token is not exist
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)); // ERC721Meta: token is not exist
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: self approval
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender())); // ERC721: 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: token is not exist
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender()); // ERC721: wrong approve
_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: wrong caller
_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: wrong caller
_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 Implementation
}
/**
* @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: token is not exist
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 implementation
}
/**
* @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: zero address
require(!_exists(tokenId)); // ERC721: 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: is not owner
require(to != address(0)); // ERC721: 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 implementation
} 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 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: 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: 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();
}
}
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
*/
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Pausable, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
mapping (address => bool) operators;
mapping (uint256 => uint256) tokenToSeries;
struct Series {
string name;
string baseURI;
uint256 start;
uint256 current;
uint256 supply;
}
Series[] collections;
event NewCollection(uint256 collection_id,string name,string baseURI,uint256 start,uint256 supply);
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
modifier ownerOrOperator() {
require(msgSender() == owner() || operators[msgSender()]); // Neither owner nor operator
_;
}
function setOperator(address _operator, bool status) external onlyOwner {
if (status) {
operators[_operator] = status;
} else {
delete operators[_operator];
}
}
function addSeries(
string[] memory _names,
string[] memory baseURIs,
uint256[] memory _starts,
uint256[] memory _supplys
) external onlyOwner {
require (_names.length == baseURIs.length); // len 1 & 2 not equal
require (_names.length == _starts.length); // len 1 & 3 not equal
require (_names.length == _supplys.length); // len 1 & 4 not equal
for (uint j = 0; j < _names.length; j++){
collections.push(Series(_names[j],baseURIs[j],_starts[j],0, _supplys[j]));
emit NewCollection(collections.length-1,_names[j],baseURIs[j],_starts[j], _supplys[j]);
}
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function preMintTo(address _to, uint256[] memory _seriesz) public ownerOrOperator {
for (uint j = 0; j < _seriesz.length; j++){
uint256 collection = _seriesz[j];
require(collection < collections.length); // Wrong collection
uint256 newTokenId = _getNextTokenId(collection);
_mint(_to, newTokenId);
tokenToSeries[newTokenId] = collection;
}
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to, uint256 collection) public ownerOrOperator {
require(collection < collections.length); // Wrong collection
uint256 newTokenId = _getNextTokenId(collection);
_mint(_to, newTokenId);
tokenToSeries[newTokenId] = collection;
}
function privateMint(address _to, uint256 collection) public onlyOwner {
require(collections[collection].supply == 250); // Wrong collection
for (uint i = 0; i < 25; i++) {
uint256 newTokenId = _getNextTokenId(collection);
_mint(_to, newTokenId);
tokenToSeries[newTokenId] = collection;
}
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId(uint256 collection) private returns (uint256) {
Series storage coll = collections[collection];
uint pointer = coll.current++;
require(pointer < coll.supply); // Not available
uint256 reply = coll.start + pointer;
return reply;
}
function baseTokenURI() virtual public view returns (string memory);
function seriesURI(uint256 collection) public view returns (string memory) {
require(collection < collections.length); // Wrong collection
return collections[collection].baseURI;
}
function seriesStart(uint256 collection) internal view returns (uint256) {
require(collection < collections.length); // Wrong collection
return collections[collection].start;
}
function seriesName(uint256 collection) public view returns (string memory) {
require(collection < collections.length); // Wrong collection
return collections[collection].name;
}
function tokenURI(uint256 _tokenId) override public view returns (string memory) {
require(_exists(_tokenId)); // Wrong collection
uint256 collection = tokenToSeries[_tokenId];
uint256 adjustedID = _tokenId - seriesStart(collection)+1;
return string(abi.encodePacked(baseTokenURI(),seriesURI(collection),"/", Strings.toString(adjustedID)));
}
function numSeries() external view returns (uint256) {
return collections.length;
}
function available(uint256 collectionId) external view returns (uint256) {
require(collectionId < collections.length); // Wrong collection
Series memory coll = collections[collectionId];
return coll.supply - coll.current;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address _owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == operator) {
return true;
}
return super.isApprovedForAll(_owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
contract RoyaltiesV2Impl is AbstractRoyalties, RoyaltiesV2 {
function getRaribleV2Royalties(uint256 id) override external view returns (LibPart.Part[] memory) {
return royalties[0];
}
function _onRoyaltiesSet(uint256 id, LibPart.Part[] memory _royalties) override internal {
emit RoyaltiesSet(id, _royalties);
}
}
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract NFTToken is ERC721Tradable, RoyaltiesV2Impl {
// Constants
bytes4 private constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
// Events
event PermanentURI(string _value, uint256 indexed _id); // OpenSea Freezing Metadata
string _tokenURI = "";
string _contractURI = "";
constructor(address _proxyRegistryAddress)
ERC721Tradable("RelatioNFT", "RelatioNFT", _proxyRegistryAddress)
{}
function baseTokenURI() override public view returns (string memory) {
return _tokenURI;
}
function transferFrom(address from, address to, uint256 tokenId) override public whenNotPaused {
super.transferFrom(from, to, tokenId);
}
function burn(uint256 tokenId) public whenNotPaused {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId));
_burn(tokenId);
}
// Updates
// OpenSea Freezing Metadata
function freezeMetadataForToken(uint256 _tokenId) public ownerOrOperator {
require(_exists(_tokenId));
string memory metadataUri = tokenURI(_tokenId);
emit PermanentURI(metadataUri, _tokenId);
}
function freezingMetadataForTokens(uint256 _collectionId, uint256 _startTokenId, uint256 _endTokenId) public ownerOrOperator {
require(_collectionId < collections.length); // Wrong collection
for (uint i = _startTokenId; i < _endTokenId + 1; i++) {
freezeMetadataForToken(i);
}
}
function setTokenURI(string memory _uri) external onlyOwner {
_tokenURI = _uri;
}
function setContractURI(string memory _uri) external onlyOwner {
_contractURI = _uri;
}
function unpause() external onlyOwner {
_unpause();
}
function pause() external onlyOwner {
_pause();
}
function setProxyRegistryAddress(address _proxyRegistryAddress) external onlyOwner {
proxyRegistryAddress = _proxyRegistryAddress;
}
// Secondary Marketplace Functions
// OpenSea
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @notice Helper allowing OpenSea gas-less trading by verifying who's operator for owner
/// @dev Allows to check if `operator` is owner's OpenSea proxy on eth mainnet / rinkeby
/// or to check if operator is OpenSea's proxy contract on Polygon and Mumbai
/// @param owner the owner we check for
/// @param operator the operator (proxy) we check for
function isOwnersOpenSeaProxy(address owner, address operator) public view returns (bool)
{
address _proxyRegistry = proxyRegistryAddress;
if (_proxyRegistry != address(0)) {
if (block.chainid == 1 || block.chainid == 4) {
return address(ProxyRegistry(_proxyRegistry).proxies(owner)) == operator;
} else if (block.chainid == 137 || block.chainid == 80001) {
return _proxyRegistry == operator;
}
}
return false;
}
// Rarible Royalties V2
function setRoyalties(uint _tokenId, address payable _royaltiesReceipientAddress, uint96 _percentageBasisPoints) public ownerOrOperator {
LibPart.Part[] memory _royalties = new LibPart.Part[](1);
_royalties[0].value = _percentageBasisPoints;
_royalties[0].account = _royaltiesReceipientAddress;
_saveRoyalties(_tokenId, _royalties);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721Enumerable) returns (bool) {
if (interfaceId == LibRoyaltiesV2._INTERFACE_ID_ROYALTIES || interfaceId == _INTERFACE_ID_EIP2981) {
return true;
}
return super.supportsInterface(interfaceId);
}
// EIP-2981 - https://eips.ethereum.org/EIPS/eip-2981
function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 amount) {
require(_exists(tokenId));
LibPart.Part[] memory royalInfo = royalties[0];
uint256 royaltyValue = royalInfo[0].value;
address royaltyAccount = royalInfo[0].account;
uint256 royaltyAmount = SafeMath.div(SafeMath.mul(salePrice, royaltyValue), 10000);
return (royaltyAccount, royaltyAmount);
}
} | EIP-2981 - https:eips.ethereum.org/EIPS/eip-2981 | function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 amount) {
require(_exists(tokenId));
LibPart.Part[] memory royalInfo = royalties[0];
uint256 royaltyValue = royalInfo[0].value;
address royaltyAccount = royalInfo[0].account;
uint256 royaltyAmount = SafeMath.div(SafeMath.mul(salePrice, royaltyValue), 10000);
return (royaltyAccount, royaltyAmount);
}
| 10,148,863 | [
1,
41,
2579,
17,
5540,
11861,
300,
2333,
30,
73,
7146,
18,
546,
822,
379,
18,
3341,
19,
41,
2579,
55,
19,
73,
625,
17,
5540,
11861,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
721,
93,
15006,
966,
12,
11890,
5034,
1147,
548,
16,
2254,
5034,
272,
5349,
5147,
13,
3903,
1476,
1135,
261,
2867,
5971,
16,
2254,
5034,
3844,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
10019,
203,
540,
203,
3639,
10560,
1988,
18,
1988,
8526,
3778,
721,
93,
287,
966,
273,
721,
93,
2390,
606,
63,
20,
15533,
203,
3639,
2254,
5034,
721,
93,
15006,
620,
273,
721,
93,
287,
966,
63,
20,
8009,
1132,
31,
203,
3639,
1758,
721,
93,
15006,
3032,
273,
721,
93,
287,
966,
63,
20,
8009,
4631,
31,
203,
3639,
2254,
5034,
721,
93,
15006,
6275,
273,
14060,
10477,
18,
2892,
12,
9890,
10477,
18,
16411,
12,
87,
5349,
5147,
16,
721,
93,
15006,
620,
3631,
12619,
1769,
203,
203,
3639,
327,
261,
3800,
15006,
3032,
16,
721,
93,
15006,
6275,
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
] |
./partial_match/1/0x21B8bfbbefc9E2b9A994871Ecd742A5132B98AeD/sources/CryptoRealEstate.sol | * @dev Withdraws tokens from the contract, excluded contract's own token. @param tokenAddress The address of the token being withdrawn. @param amount The amount of tokens being withdrawn./ | function withdrawToken(address tokenAddress, uint256 amount) external onlyOwner {
require(tokenAddress != address(this), "Cannot withdraw contract's own token");
IERC20 token = IERC20(tokenAddress);
require(token.balanceOf(address(this)) >= amount, "Insufficient balance");
token.safeTransfer(msg.sender, amount);
emit WithdrawedToken(msg.sender, tokenAddress, amount);
}
The threshold is specified as a percentage of the initial total supply.
The provided `_newThreshold` value is multiplied by 10^20 to fit the format: 300 = 0.03%.
| 4,289,845 | [
1,
1190,
9446,
87,
2430,
628,
326,
6835,
16,
8845,
6835,
1807,
4953,
1147,
18,
225,
1147,
1887,
1021,
1758,
434,
326,
1147,
3832,
598,
9446,
82,
18,
225,
3844,
1021,
3844,
434,
2430,
3832,
598,
9446,
82,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
598,
9446,
1345,
12,
2867,
1147,
1887,
16,
2254,
5034,
3844,
13,
3903,
1338,
5541,
288,
203,
565,
2583,
12,
2316,
1887,
480,
1758,
12,
2211,
3631,
315,
4515,
598,
9446,
6835,
1807,
4953,
1147,
8863,
203,
565,
467,
654,
39,
3462,
1147,
273,
467,
654,
39,
3462,
12,
2316,
1887,
1769,
203,
565,
2583,
12,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
3844,
16,
315,
5048,
11339,
11013,
8863,
203,
565,
1147,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
3626,
3423,
9446,
329,
1345,
12,
3576,
18,
15330,
16,
1147,
1887,
16,
3844,
1769,
203,
225,
289,
203,
203,
565,
1021,
5573,
353,
1269,
487,
279,
11622,
434,
326,
2172,
2078,
14467,
18,
203,
565,
1021,
2112,
1375,
67,
2704,
7614,
68,
460,
353,
27789,
635,
1728,
66,
3462,
358,
4845,
326,
740,
30,
11631,
273,
374,
18,
4630,
9,
18,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/43113/0xA0603C9fD66420146A24a98fDEf6a74F54210210/sources/contracts/BeethovenxMasterChef.sol | BEETHOVEn tokens created per block. | uint256 public beetxPerBlock;
| 16,907,420 | [
1,
5948,
1584,
7995,
58,
664,
2430,
2522,
1534,
1203,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
506,
278,
92,
2173,
1768,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x5256308608B6865F486b59136e7826ACF648a2a1/sources/contracts/prebuilts/account/utils/AccountCore.sol | @notice Initializes the smart contract wallet. This is passed as data in the `_registerOnFactory()` call in `AccountExtension` / `Account`. | function initialize(address _defaultAdmin, bytes calldata) public virtual initializer {
AccountCoreStorage.data().firstAdmin = _defaultAdmin;
_setAdmin(_defaultAdmin, true);
}
Events
event EntrypointOverride(IEntryPoint entrypointOverride);
| 1,960,700 | [
1,
9685,
326,
13706,
6835,
9230,
18,
1220,
353,
2275,
487,
501,
316,
326,
1375,
67,
4861,
1398,
1733,
20338,
745,
316,
1375,
3032,
3625,
68,
342,
1375,
3032,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
2867,
389,
1886,
4446,
16,
1731,
745,
892,
13,
1071,
5024,
12562,
288,
203,
3639,
6590,
4670,
3245,
18,
892,
7675,
3645,
4446,
273,
389,
1886,
4446,
31,
203,
3639,
389,
542,
4446,
24899,
1886,
4446,
16,
638,
1769,
203,
565,
289,
203,
203,
27573,
9043,
203,
565,
871,
3841,
1153,
6618,
12,
45,
1622,
2148,
26076,
6618,
1769,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.4.24;
import "./ownership/Ownable.sol";
import "./lifecycle/Destructible.sol";
import "./tokenutils/CanRescueERC20.sol";
/**
* Simple Public Voting/Poll Demo
*
* This is a DEMO contract. Please look carefully into the source code
* before using any of this in production.
*
*
* Disclaimer of Warranty:
* THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
* EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
* PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
* PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
* NECESSARY SERVICING, REPAIR OR CORRECTION.
*
*/
contract Voting is Ownable, Destructible, CanRescueERC20 {
/**
* @dev number of possible choices. Constant set at compile time.
*/
uint8 internal constant NUMBER_OF_CHOICES = 4;
/**
* @notice Number of total cast votes (uint40 is enough as at most
* we support 4 choices and 2^32 votes per choice).
*/
uint40 public voteCountTotal;
/**
* @notice Number of votes, summarized per choice.
*
* @dev uint32 allows 4,294,967,296 possible votes per choice, should be enough,
* and still allows 8 entries to be packed in a single storage slot
* (EVM wordsize is 256 bit). And of course we check for overflows.
*/
uint32[NUMBER_OF_CHOICES] internal currentVoteResults;
/**
* @notice Mapping of address to vote details
*/
mapping(address => Voter) public votersInfo;
/**
* @notice Event gets emitted every time when a new vote is cast.
*
* @param addedVote choice in the vote
* @param allVotes array containing updated intermediate result
*/
event NewVote(uint8 indexed addedVote, uint32[NUMBER_OF_CHOICES] allVotes);
/**
* @dev Represent info about a single voter.
*/
struct Voter {
bool exists;
uint8 choice;
string name;
}
/**
* @notice Fallback function. Will be called whenever the contract receives ether, or
* when is called without data or with unknown function signature.
*/
function()
public {
}
/**
* @notice Cast your note. In a real world scenario, you might want to have address
* voting only once. In this DEMO we allow unlimited number of votes per address.
* @param voterName Name of the voter, will be publicly visible on the blockchain
* @param givenVote choice the caller has voted for
*/
function castVote(string voterName, uint8 givenVote)
external {
// answer must be given
require(givenVote < numberOfChoices(), "Choice must be less than contract configured numberOfChoices.");
// DEMO MODE: FOR EASIER TESTING, WE ALLOW UNLIMITED VOTES PER ADDRESS.
// check if already voted
//require(!votersInfo[msg.sender].exists, "This address has already voted. Vote denied.");
// voter name has to have at least 3 bytes (note: with utf8 some chars have
// more than 1 byte, so this check is not fully accurate but ok here)
require(bytes(voterName).length > 2, "Name of voter is too short.");
// everything ok, add voter
votersInfo[msg.sender] = Voter(true, givenVote, voterName);
voteCountTotal = safeAdd40(voteCountTotal, 1);
currentVoteResults[givenVote] = safeAdd32(currentVoteResults[givenVote], 1);
// emit a NewVote event at this point in time, so that a web3 Dapp
// can react it to it immediately. Emit full current vote state, as
// events are cheaper for light clients than querying the state.
emit NewVote(givenVote, currentVoteResults);
}
/**
* @notice checks if this address has already cast a vote
* this is required to find out if it is safe to call the other "thisVoters..." views.
*/
function thisVoterExists()
external
view
returns (bool) {
return votersInfo[msg.sender].exists;
}
/**
* @notice Returns the vote details of calling address or throws
* if address has not voted yet.
*/
function thisVotersChoice()
external
view
returns (uint8) {
// check if msg sender exists in voter mapping
require(votersInfo[msg.sender].exists, "No vote so far.");
return votersInfo[msg.sender].choice;
}
/**
* @notice Returns the entered voter name of the calling address or throws
* if address has not voted yet.
*/
function thisVotersName()
external
view
returns (string) {
// check if msg sender exists in voter mapping
require(votersInfo[msg.sender].exists, "No vote so far.");
return votersInfo[msg.sender].name;
}
/**
* @notice Return array with sums of votes per choice.
*
* @dev Note that this only will work for external callers, and not
* for other contracts (as of solidity 0.4.25 returning of dynamically
* sized data is still not in stable, it's only available with the
* experimental "ABIEncoderV2" pragma). Also some block-explorers,
* like etherscan, will have problems to display this correctly.
*/
function currentResult()
external
view
returns (uint32[NUMBER_OF_CHOICES]) {
return currentVoteResults;
}
/**
* @notice Return number of votes for one of the options.
*/
function votesPerChoice(uint8 option)
external
view
returns (uint32) {
require(option < numberOfChoices(), "Choice must be less than contract configured numberOfChoices.");
return currentVoteResults[option];
}
/**
* @notice Returns the number of possible choices, which can be voted for.
*/
function numberOfChoices()
public
view
returns (uint8) {
// save as we only initialize array length in constructor
// and there we check it's never larger than uint8.
return uint8(currentVoteResults.length);
}
/**
* @dev Adds two uint40 numbers, throws on overflow.
*/
function safeAdd40(uint40 _a, uint40 _b)
internal
pure
returns (uint40 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
/**
* @dev Adds two uint32 numbers, throws on overflow.
*/
function safeAdd32(uint32 _a, uint32 _b)
internal
pure
returns (uint32 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
| * @notice Fallback function. Will be called whenever the contract receives ether, or when is called without data or with unknown function signature./ | function()
public {
}
| 1,057,877 | [
1,
12355,
445,
18,
9980,
506,
2566,
17334,
326,
6835,
17024,
225,
2437,
16,
578,
377,
1347,
353,
2566,
2887,
501,
578,
598,
5917,
445,
3372,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
203,
565,
1071,
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
] |
./full_match/5/0x7592Ad541bEcaD094A32Fe1D4816F210652Fa5DF/sources/project_/contracts/Nft1155.sol | import "./access/Ownable.sol";import "./ERC1155.sol"; | import "./presets/ERC1155PresetMinterPauser.sol";
| 11,591,343 | [
1,
5666,
25165,
3860,
19,
5460,
429,
18,
18281,
14432,
5666,
25165,
654,
39,
2499,
2539,
18,
18281,
14432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
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,
5666,
25165,
12202,
2413,
19,
654,
39,
2499,
2539,
18385,
49,
2761,
16507,
1355,
18,
18281,
14432,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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;
interface AggregatorV3Interface {
function decimals()
external
view
returns (
uint8
);
function description()
external
view
returns (
string memory
);
function version()
external
view
returns (
uint256
);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import "../Token/ERC20/IERC20.sol";
// TODO. Mañana comentar todas las funciones...
contract XifraICO {
address immutable private xifraWallet; // Xifra wallet
address immutable private xifraToken; // Xifra token address
address immutable private usdtToken; // USDT token address
address immutable private usdcToken; // USDC token address
uint256 immutable private minTokensBuyAllowed; // Minimum tokens allowed
uint256 immutable private maxICOTokens; // Max ICO tokens to sell
uint256 immutable private icoStartDate; // ICO start date
uint256 immutable private icoEndDate; // ICO end date
AggregatorV3Interface internal priceFeed; // Chainlink price feeder ETH/USD
uint256 public icoTokensBought; // Tokens sold
uint256 public tokenListingDate; // Token listing date
mapping(address => uint256) private userBoughtTokens; // Mapping to store all the buys
mapping(address => uint256) private userWithdrawTokens; // Mapping to store the user tokens withdraw
bool private icoFinished;
uint32 internal constant _1_MONTH_IN_SECONDS = 2592000;
uint32 internal constant _3_MONTHS_IN_SECONDS = 3 * _1_MONTH_IN_SECONDS;
uint32 internal constant _6_MONTHS_IN_SECONDS = 6 * _1_MONTH_IN_SECONDS;
uint32 internal constant _9_MONTHS_IN_SECONDS = 9 * _1_MONTH_IN_SECONDS;
uint256 internal constant _MIN_COINS_FOR_VESTING = 26667 * 10 ** 18;
event onTokensBought(address _buyer, uint256 _tokens, uint256 _paymentAmount, address _tokenPayment);
event onWithdrawICOFunds(uint256 _usdtBalance, uint256 _usdcBalance, uint256 _ethbalance);
event onWithdrawBoughtTokens(address _user, uint256 _maxTokensAllowed);
event onICOFinished(uint256 _date);
/**
* @notice Constructor
* @param _wallet --> Xifra master wallet
* @param _token --> Xifra token address
* @param _icoStartDate --> ICO start date
* @param _icoEndDate --> ICO end date
* @param _usdtToken --> USDT token address
* @param _usdcToken --> USDC token address
* @param _minTokensBuyAllowed --> Minimal amount of tokens allowed to buy
* @param _maxICOTokens --> Number of tokens selling in this ICO
* @param _tokenListingDate --> Token listing date for the ICO vesting
*/
constructor(address _wallet, address _token, uint256 _icoStartDate, uint256 _icoEndDate, address _usdtToken, address _usdcToken, uint256 _minTokensBuyAllowed, uint256 _maxICOTokens, uint256 _tokenListingDate) {
xifraWallet = _wallet;
xifraToken = _token;
icoStartDate = _icoStartDate;
icoEndDate = _icoEndDate;
usdtToken = _usdtToken;
usdcToken = _usdcToken;
minTokensBuyAllowed = _minTokensBuyAllowed;
maxICOTokens = _maxICOTokens;
tokenListingDate = _tokenListingDate;
if (_getChainId() == 1) priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
else if (_getChainId() == 4) priceFeed = AggregatorV3Interface(0x8A753747A1Fa494EC906cE90E9f37563A8AF630e);
}
/**
* @notice Buy function. Used to buy tokens using ETH, USDT or USDC
* @param _paymentAmount --> Result of multiply number of tokens to buy per price per token. Must be always multiplied per 1000 to avoid decimals
* @param _tokenPayment --> Address of the payment token (or 0x0 if payment is ETH)
*/
function buy(uint256 _paymentAmount, address _tokenPayment) external payable {
require(_isICOActive() == true, "ICONotActive");
uint256 paidTokens = 0;
if (msg.value == 0) {
// Stable coin payment
require(_paymentAmount > 0, "BadPayment");
require(_tokenPayment == usdtToken || _tokenPayment == usdcToken, "TokenNotSupported");
require(IERC20(_tokenPayment).transferFrom(msg.sender, address(this), _paymentAmount));
paidTokens = _paymentAmount * 2666666666666666667 / 1000000000000000000; // 0.375$ per token in the ICO
} else {
// ETH Payment
uint256 usdETH = _getUSDETHPrice();
uint256 paidUSD = msg.value * usdETH / 10**18;
paidTokens = paidUSD * 2666666666666666666 / 1000000000000000000; // 0.375$ per token in the ICO
}
require((paidTokens + 1*10**18) >= minTokensBuyAllowed, "BadTokensQuantity"); // One extra token as threshold rounding decimals
require(maxICOTokens - icoTokensBought >= paidTokens, "NoEnoughTokensInICO");
userBoughtTokens[msg.sender] += paidTokens;
icoTokensBought += paidTokens;
if (maxICOTokens - icoTokensBought < minTokensBuyAllowed) {
// We finish the ICO
icoFinished = true;
emit onICOFinished(block.timestamp);
}
emit onTokensBought(msg.sender, paidTokens, _paymentAmount, _tokenPayment);
}
/**
* @notice Withdraw user tokens when the vesting rules allow it
*/
function withdrawBoughtTokens() external {
require(_isICOActive() == false, "ICONotActive");
require(userBoughtTokens[msg.sender] > 0, "NoBalance");
require(block.timestamp >= tokenListingDate, "TokenNoListedYet");
uint256 boughtBalance = userBoughtTokens[msg.sender];
uint256 maxTokensAllowed = 0;
if ((block.timestamp >= tokenListingDate) && (block.timestamp < tokenListingDate + _3_MONTHS_IN_SECONDS)) {
if (boughtBalance <= _MIN_COINS_FOR_VESTING) {
maxTokensAllowed = boughtBalance - userWithdrawTokens[msg.sender];
} else {
uint maxTokens = boughtBalance * 25 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
}
} else if ((block.timestamp >= tokenListingDate + _3_MONTHS_IN_SECONDS) && (block.timestamp < tokenListingDate + _6_MONTHS_IN_SECONDS)) {
uint256 maxTokens = boughtBalance * 50 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
} else if ((block.timestamp >= tokenListingDate + _6_MONTHS_IN_SECONDS) && (block.timestamp < tokenListingDate + _9_MONTHS_IN_SECONDS)) {
uint256 maxTokens = boughtBalance * 75 / 100;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
} else {
uint256 maxTokens = boughtBalance;
if (userWithdrawTokens[msg.sender] < maxTokens) {
maxTokensAllowed = maxTokens - userWithdrawTokens[msg.sender];
}
}
require(maxTokensAllowed > 0, "NoTokensToWithdraw");
userWithdrawTokens[msg.sender] += maxTokensAllowed;
require(IERC20(xifraToken).transfer(msg.sender, maxTokensAllowed));
emit onWithdrawBoughtTokens(msg.sender, maxTokensAllowed);
}
/**
* @notice Returns the crypto numbers and balance in the ICO contract
*/
function withdrawICOFunds() external {
require(_isICOActive() == false, "ICONotActive");
uint256 usdtBalance = IERC20(usdtToken).balanceOf(address(this));
require(IERC20(usdtToken).transfer(xifraWallet, usdtBalance));
uint256 usdcBalance = IERC20(usdcToken).balanceOf(address(this));
require(IERC20(usdcToken).transfer(xifraWallet, usdcBalance));
uint256 ethbalance = address(this).balance;
payable(xifraWallet).transfer(ethbalance);
emit onWithdrawICOFunds(usdtBalance, usdcBalance, ethbalance);
}
/**
* @notice Withdraw the unsold Xifra tokens to the Xifra wallet when the ICO is finished
*/
function withdrawICOTokens() external {
require(_isICOActive() == false, "ICONotActive");
require(msg.sender == xifraWallet, "OnlyXifra");
uint256 balance = maxICOTokens - icoTokensBought;
require(IERC20(xifraToken).transfer(xifraWallet, balance));
}
/**
* @notice OnlyOwner function. Change the listing date to start the vesting
* @param _tokenListDate --> New listing date in UnixDateTime UTC format
*/
function setTokenListDate(uint256 _tokenListDate) external {
require(msg.sender == xifraWallet, "BadOwner");
require(block.timestamp <= tokenListingDate, "TokenListedYet");
tokenListingDate = _tokenListDate;
}
/**
* @notice Returns the number of tokens and user has bought
* @param _user --> User account
* @return Returns the user token balance in wei units
*/
function getUserBoughtTokens(address _user) external view returns(uint256) {
return userBoughtTokens[_user];
}
/**
* @notice Returns the number of tokens and user has withdrawn
* @param _user --> User account
* @return Returns the user token withdrawns in wei units
*/
function getUserWithdrawnTokens(address _user) external view returns(uint256) {
return userWithdrawTokens[_user];
}
/**
* @notice Returns the crypto numbers in the ICO
* @return xifra Returns the Xifra tokens balance in the contract
* @return eth Returns the ETHs balance in the contract
* @return usdt Returns the USDTs balance in the contract
* @return usdc Returns the USDCs balance in the contract
*/
function getICOData() external view returns(uint256 xifra, uint256 eth, uint256 usdt, uint256 usdc) {
xifra = IERC20(xifraToken).balanceOf(address(this));
usdt = IERC20(usdtToken).balanceOf(address(this));
usdc = IERC20(usdcToken).balanceOf(address(this));
eth = address(this).balance;
}
/**
* @notice Traslate a payment in USD to ETHs
* @param _paymentAmount --> Payment amount in USD
* @return Returns the ETH amount in weis
*/
function calculateETHPayment(uint256 _paymentAmount) external view returns(uint256) {
uint256 usdETH = _getUSDETHPrice();
return (_paymentAmount * 10 ** 18) / usdETH;
}
/**
* @notice Get the vesting unlock dates
* @param _period --> There are 4 periods (0,1,2,3)
* @return _date Returns the date in UnixDateTime UTC format
*/
function getVestingDate(uint256 _period) external view returns(uint256 _date) {
if (_period == 0) {
_date = tokenListingDate;
} else if (_period == 1) {
_date = tokenListingDate + _3_MONTHS_IN_SECONDS;
} else if (_period == 2) {
_date = tokenListingDate + _6_MONTHS_IN_SECONDS;
} else if (_period == 3) {
_date = tokenListingDate + _9_MONTHS_IN_SECONDS;
}
}
/**
* @notice Public function that returns ETHUSD par
* @return Returns the how much USDs are in 1 ETH in weis
*/
function getUSDETHPrice() external view returns(uint256) {
return _getUSDETHPrice();
}
/**
* @notice Uses Chainlink to query the USDETH price
* @return Returns the ETH amount in weis (Fixed value of 3932.4 USDs in localhost development environments)
*/
function _getUSDETHPrice() internal view returns(uint256) {
int price = 0;
if (address(priceFeed) != address(0)) {
(, price, , , ) = priceFeed.latestRoundData();
} else {
// For local testing
price = 393240000000;
}
return uint256(price * 10**10);
}
/**
* @notice Internal function that queries the chainId
* @return Returns the chainId (1 - Mainnet, 4 - Rinkeby testnet)
*/
function _getChainId() internal view returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
/**
* @notice Internal - Is ICO active?
* @return Returns true or false
*/
function _isICOActive() internal view returns(bool) {
if ((block.timestamp < icoStartDate) || (block.timestamp > icoEndDate) || (icoFinished == true)) return false;
else return true;
}
/**
* @notice External - Is ICO active?
* @return Returns true or false
*/
function isICOActive() external view returns(bool) {
return _isICOActive();
}
}
// 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);
}
| * @notice Internal function that queries the chainId @return Returns the chainId (1 - Mainnet, 4 - Rinkeby testnet)/ | function _getChainId() internal view returns (uint256) {
uint256 chainId;
return chainId;
}
| 10,214,175 | [
1,
3061,
445,
716,
6218,
326,
2687,
548,
327,
2860,
326,
2687,
548,
261,
21,
300,
12740,
2758,
16,
1059,
300,
534,
754,
73,
1637,
1842,
2758,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
389,
588,
3893,
548,
1435,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
3639,
327,
2687,
548,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x8f12e8dfE0b4251b67896366410bB5521d709b61/sources/@tsb/exchange/contracts/WhiteList.sol | @notice add token to the ERC20 list @param tokenAddress token address | function addERC20(address tokenAddress) external onlyOwner {
grantRole(ERC20_ROLE, tokenAddress);
}
| 5,619,172 | [
1,
1289,
1147,
358,
326,
4232,
39,
3462,
666,
225,
1147,
1887,
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
] | [
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,
527,
654,
39,
3462,
12,
2867,
1147,
1887,
13,
3903,
1338,
5541,
288,
203,
3639,
7936,
2996,
12,
654,
39,
3462,
67,
16256,
16,
1147,
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,
-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-21
*/
// File: contracts/interfaces/ISaffronBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.1;
interface ISaffronBase {
enum Tranche {S, AA, A}
enum LPTokenType {dsec, principal}
// Store values (balances, dsec, vdsec) with TrancheUint256
struct TrancheUint256 {
uint256 S;
uint256 AA;
uint256 A;
}
struct epoch_params {
uint256 start_date; // Time when the platform launched
uint256 duration; // Duration of epoch
}
}
// File: contracts/interfaces/ISaffronStrategy.sol
pragma solidity ^0.7.1;
interface ISaffronStrategy is ISaffronBase{
function deploy_all_capital() external;
function select_adapter_for_liquidity_removal() external returns(address);
function add_adapter(address adapter_address) external;
function add_pool(address pool_address) external;
function delete_adapters() external;
function set_governance(address to) external;
function get_adapter_address(uint256 adapter_index) external view returns(address);
function set_pool_SFI_reward(uint256 poolIndex, uint256 reward) external;
}
// File: contracts/interfaces/ISaffronPool.sol
pragma solidity ^0.7.1;
interface ISaffronPool is ISaffronBase {
function add_liquidity(uint256 amount, Tranche tranche) external;
function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external;
function get_base_asset_address() external view returns(address);
function hourly_strategy(address adapter_address) external;
function wind_down_epoch(uint256 epoch, uint256 amount_sfi) external;
function set_governance(address to) external;
function get_epoch_cycle_params() external view returns (uint256, uint256);
function shutdown() external;
}
// File: contracts/interfaces/ISaffronAdapter.sol
pragma solidity ^0.7.1;
interface ISaffronAdapter is ISaffronBase {
function deploy_capital(uint256 amount) external;
function return_capital(uint256 base_asset_amount, address to) external;
function approve_transfer(address addr,uint256 amount) external;
function get_base_asset_address() external view returns(address);
function set_base_asset(address addr) external;
function get_holdings() external returns(uint256);
function get_interest(uint256 principal) external returns(uint256);
function set_governance(address to) external;
}
// File: contracts/lib/IERC20.sol
pragma solidity ^0.7.1;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/lib/SafeMath.sol
pragma solidity ^0.7.1;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/lib/Address.sol
pragma solidity ^0.7.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
* ====
*/
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.3._
*/
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.3._
*/
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: contracts/lib/SafeERC20.sol
pragma solidity ^0.7.1;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/lib/Context.sol
pragma solidity ^0.7.1;
/*
* @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: contracts/lib/ERC20.sol
pragma solidity ^0.7.1;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/SFI.sol
pragma solidity ^0.7.1;
contract SFI is ERC20 {
using SafeERC20 for IERC20;
address public governance;
address public SFI_minter;
uint256 public MAX_TOKENS = 100000 ether;
constructor (string memory name, string memory symbol) ERC20(name, symbol) {
// Initial governance is Saffron Deployer
governance = msg.sender;
}
function mint_SFI(address to, uint256 amount) public {
require(msg.sender == SFI_minter, "must be SFI_minter");
require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS");
_mint(to, amount);
}
function set_minter(address to) external {
require(msg.sender == governance, "must be governance");
SFI_minter = to;
}
function set_governance(address to) external {
require(msg.sender == governance, "must be governance");
governance = to;
}
event ErcSwept(address who, address to, address token, uint256 amount);
function erc_sweep(address _token, address _to) public {
require(msg.sender == governance, "must be governance");
IERC20 tkn = IERC20(_token);
uint256 tBal = tkn.balanceOf(address(this));
tkn.safeTransfer(_to, tBal);
emit ErcSwept(msg.sender, _to, _token, tBal);
}
}
// File: contracts/SaffronStrategy.sol
pragma solidity ^0.7.1;
// v0: all functions returns the only adapter that exists
// v1: evaluate adapters by interest rate and return the best one possible per currency
contract SaffronStrategy is ISaffronStrategy {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public governance;
address public team_address;
address public SFI_address;
address[] public pools;
address[] public adapters;
mapping(address=>uint256) private adapter_indexes;
mapping(uint256=>address) private adapter_addresses;
uint256[] public pool_SFI_rewards = [
10500000000000000000, // 10.5 SFI - dai comp
33750000000000000000, // 33.75 SFI - eth uni
22500000000000000000, // 22.5 SFI - sfi stake
1500000000000000000 , // 1.5 SFI - btse
10500000000000000000, // 10.5 SFI - wbtc comp
1500000000000000000, // 1.5 SFI - geeq
1500000000000000000, // 1.5 SFI - esd
33750000000000000000, // 33.75 SFI - eth sushi
1500000000000000000, // 1.5 SFI - alpha
10500000000000000000, // 10.5 SFI - dai rari
1500000000000000000, // 1.5 SFI - prt
10500000000000000000, // 10.5 SFI - usdt comp
10500000000000000000 // 10.5 SFI - usdc comp
];
// True if epoch has been wound down already
mapping(uint256=>bool) public epoch_wound_down;
uint256 public last_deploy; // Last run of Hourly Deploy
uint256 public deploy_interval; // Hourly deploy interval
epoch_params public epoch_cycle = epoch_params({
start_date: 1604239200, // 11/01/2020 @ 2:00pm (UTC)
duration: 14 days // 1210000 seconds
});
constructor(address _sfi_address, address _team_address, bool epoch_cycle_reset) {
governance = msg.sender;
team_address = _team_address;
SFI_address = _sfi_address;
deploy_interval = 1 hours;
epoch_cycle.duration = (epoch_cycle_reset ? 30 minutes : 14 days); // Make testing previous epochs easier
epoch_cycle.start_date = (epoch_cycle_reset ? (block.timestamp) - (4 * epoch_cycle.duration) : 1604239200); // Make testing previous epochs easier
}
function wind_down_epoch(uint256 epoch) external {
require(epoch == 10, "v1.10: only epoch 10");
require(!epoch_wound_down[epoch], "epoch already wound down");
require(msg.sender == team_address || msg.sender == governance, "must be team or governance");
uint256 current_epoch = get_current_epoch();
require(epoch < current_epoch, "cannot wind down future epoch");
epoch_wound_down[epoch] = true;
// Team Funds - https://miro.medium.com/max/568/1*8vnnKp4JzzCA3tNqW246XA.png
uint256 team_sfi = 50 * 1 ether;
SFI(SFI_address).mint_SFI(team_address, team_sfi);
for (uint256 i = 0; i < pools.length; i++) {
uint256 rewardSFI = 0;
if (i < pool_SFI_rewards.length) {
rewardSFI = pool_SFI_rewards[i];
SFI(SFI_address).mint_SFI(pools[i], rewardSFI);
}
ISaffronPool(pools[i]).wind_down_epoch(epoch, rewardSFI);
}
}
// Wind down pool exists just in case one of the pools is broken
function wind_down_pool(uint256 pool, uint256 epoch) external {
require(msg.sender == team_address || msg.sender == governance, "must be team or governance");
require(epoch == 10, "v1.10: only epoch 10");
uint256 current_epoch = get_current_epoch();
require(epoch < current_epoch, "cannot wind down future epoch");
if (pool == uint(-1)) {
require(!epoch_wound_down[epoch], "epoch already wound down");
epoch_wound_down[epoch] = true;
// Team Funds
uint256 team_sfi = (10000 * 1 ether) >> epoch;
SFI(SFI_address).mint_SFI(team_address, team_sfi);
} else {
uint256 rewardSFI = 0;
if (pool < pool_SFI_rewards.length) {
rewardSFI = pool_SFI_rewards[pool];
SFI(SFI_address).mint_SFI(pools[pool], rewardSFI);
}
ISaffronPool(pools[pool]).wind_down_epoch(epoch, rewardSFI);
}
}
// Deploy all capital in pool (funnel 100% of pooled base assets into best adapter)
function deploy_all_capital() external override {
require(block.timestamp >= last_deploy + (deploy_interval), "deploy call too soon" );
last_deploy = block.timestamp;
// DAI/Compound
ISaffronPool pool = ISaffronPool(pools[0]);
IERC20 base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[0]) > 0) pool.hourly_strategy(adapters[0]);
// DAI/Rari
pool = ISaffronPool(pools[9]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[9]) > 0) pool.hourly_strategy(adapters[1]);
// wBTC/Compound
pool = ISaffronPool(pools[4]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[4]) > 0) pool.hourly_strategy(adapters[2]);
// USDT/Compound
pool = ISaffronPool(pools[11]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[11]) > 0) pool.hourly_strategy(adapters[3]);
// USDC/Compound
pool = ISaffronPool(pools[12]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[12]) > 0) pool.hourly_strategy(adapters[4]);
}
function deploy_all_capital_single_pool(uint256 pool_index, uint256 adapter_index) public {
require(msg.sender == governance, "must be governance");
ISaffronPool pool = ISaffronPool(pools[pool_index]);
IERC20 base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[pool_index]) > 0) pool.hourly_strategy(adapters[adapter_index]);
}
function v01_final_deploy() external {
require(msg.sender == governance, "must be governance");
// DAI Compound
ISaffronPool pool = ISaffronPool(pools[0]);
IERC20 base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[0]) > 0) pool.hourly_strategy(adapters[0]);
// Rari
pool = ISaffronPool(pools[9]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[9]) > 0) pool.hourly_strategy(adapters[1]);
// wBTC/Compound
pool = ISaffronPool(pools[4]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[4]) > 0) pool.hourly_strategy(adapters[2]);
// USDT/Compound
pool = ISaffronPool(pools[11]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[11]) > 0) pool.hourly_strategy(adapters[3]);
// USDC/Compound
pool = ISaffronPool(pools[12]);
base_asset = IERC20(pool.get_base_asset_address());
if (base_asset.balanceOf(pools[12]) > 0) pool.hourly_strategy(adapters[4]);
for (uint256 i = 0; i < pools.length; i++) {
ISaffronPool(pools[i]).shutdown();
}
}
// Add adapters to a list of adapters passed in
function add_adapter(address adapter_address) external override {
require(msg.sender == governance, "add_adapter: must be governance");
adapter_indexes[adapter_address] = adapters.length;
adapters.push(adapter_address);
}
// Get an adapter's address by index
function get_adapter_index(address adapter_address) public view returns(uint256) {
return adapter_indexes[adapter_address];
}
// Get an adapter's address by index
function get_adapter_address(uint256 index) external view override returns(address) {
return address(adapters[index]);
}
function add_pool(address pool_address) external override {
require(msg.sender == governance, "add_pool: must be governance");
pools.push(pool_address);
}
function delete_adapters() external override {
require(msg.sender == governance, "delete_adapters: must be governance");
delete adapters;
}
function set_team_address(address to) public {
require(msg.sender == governance || msg.sender == team_address, "permission");
team_address = to;
}
function set_governance(address to) external override {
require(msg.sender == governance, "set_governance: must be governance");
governance = to;
}
function set_pool_SFI_reward(uint256 poolIndex, uint256 reward) external override {
require(msg.sender == governance, "set_governance: must be governance");
pool_SFI_rewards[poolIndex] = reward;
}
function shutdown_pool(uint256 poolIndex) external {
require(msg.sender == governance, "must be governance");
ISaffronPool(pools[poolIndex]).shutdown();
}
function select_adapter_for_liquidity_removal() external view override returns(address) {
return adapters[0]; // v0: only one adapter
}
// v1.5 add replace adapter function
// v1.5 add remove adapter function
/*** TIME UTILITY FUNCTIONS ***/
function get_epoch_end(uint256 epoch) public view returns (uint256) {
return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration));
}
function get_current_epoch() public view returns (uint256) {
require(block.timestamp > epoch_cycle.start_date, "before epoch 0");
return (block.timestamp - epoch_cycle.start_date) / epoch_cycle.duration;
}
function get_seconds_until_epoch_end(uint256 epoch) public view returns (uint256) {
return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp);
}
event ErcSwept(address who, address to, address token, uint256 amount);
function erc_sweep(address _token, address _to) public {
require(msg.sender == governance, "must be governance");
IERC20 tkn = IERC20(_token);
uint256 tBal = tkn.balanceOf(address(this));
tkn.safeTransfer(_to, tBal);
emit ErcSwept(msg.sender, _to, _token, tBal);
}
} | Wind down pool exists just in case one of the pools is broken Team Funds | function wind_down_pool(uint256 pool, uint256 epoch) external {
require(msg.sender == team_address || msg.sender == governance, "must be team or governance");
require(epoch == 10, "v1.10: only epoch 10");
uint256 current_epoch = get_current_epoch();
require(epoch < current_epoch, "cannot wind down future epoch");
if (pool == uint(-1)) {
require(!epoch_wound_down[epoch], "epoch already wound down");
epoch_wound_down[epoch] = true;
uint256 team_sfi = (10000 * 1 ether) >> epoch;
SFI(SFI_address).mint_SFI(team_address, team_sfi);
uint256 rewardSFI = 0;
if (pool < pool_SFI_rewards.length) {
rewardSFI = pool_SFI_rewards[pool];
SFI(SFI_address).mint_SFI(pools[pool], rewardSFI);
}
ISaffronPool(pools[pool]).wind_down_epoch(epoch, rewardSFI);
}
}
| 2,067,996 | [
1,
59,
728,
2588,
2845,
1704,
2537,
316,
648,
1245,
434,
326,
16000,
353,
12933,
10434,
478,
19156,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
17064,
67,
2378,
67,
6011,
12,
11890,
5034,
2845,
16,
2254,
5034,
7632,
13,
3903,
288,
203,
565,
2583,
12,
3576,
18,
15330,
422,
5927,
67,
2867,
747,
1234,
18,
15330,
422,
314,
1643,
82,
1359,
16,
315,
11926,
506,
5927,
578,
314,
1643,
82,
1359,
8863,
203,
565,
2583,
12,
12015,
422,
1728,
16,
315,
90,
21,
18,
2163,
30,
1338,
7632,
1728,
8863,
203,
565,
2254,
5034,
783,
67,
12015,
273,
336,
67,
2972,
67,
12015,
5621,
203,
565,
2583,
12,
12015,
411,
783,
67,
12015,
16,
315,
12892,
17064,
2588,
3563,
7632,
8863,
203,
203,
565,
309,
261,
6011,
422,
2254,
19236,
21,
3719,
288,
203,
1377,
2583,
12,
5,
12015,
67,
91,
772,
67,
2378,
63,
12015,
6487,
315,
12015,
1818,
341,
772,
2588,
8863,
203,
1377,
7632,
67,
91,
772,
67,
2378,
63,
12015,
65,
273,
638,
31,
203,
203,
1377,
2254,
5034,
5927,
67,
21668,
77,
273,
261,
23899,
380,
404,
225,
2437,
13,
1671,
7632,
31,
203,
1377,
348,
1653,
12,
55,
1653,
67,
2867,
2934,
81,
474,
67,
55,
1653,
12,
10035,
67,
2867,
16,
5927,
67,
21668,
77,
1769,
203,
1377,
2254,
5034,
19890,
55,
1653,
273,
374,
31,
203,
1377,
309,
261,
6011,
411,
2845,
67,
55,
1653,
67,
266,
6397,
18,
2469,
13,
288,
203,
3639,
19890,
55,
1653,
273,
2845,
67,
55,
1653,
67,
266,
6397,
63,
6011,
15533,
203,
3639,
348,
1653,
12,
55,
1653,
67,
2867,
2934,
81,
474,
67,
55,
1653,
12,
27663,
63,
6011,
6487,
19890,
2
] |
./partial_match/1/0x7854d9465cf34a781404bdA2AEAd93441e998c54/sources/Coin.sol | * @dev Returns the name of the token./ | function name() public view virtual returns (string memory) {
return _MYname;
}
| 4,421,673 | [
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,
565,
445,
508,
1435,
1071,
1476,
5024,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
22114,
529,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.5;
contract rsvp {
address owner;
bool public currentEvent;
uint rsvpCost;
address[] RSVPs;
mapping(address => bool) RSVPstatus;
address[] checkedInAddresses;
mapping(address => bool) checkedIn;
constructor() {
owner = msg.sender;
currentEvent = false;
}
modifier onlyOwner() {
require(owner == msg.sender, "Only the event organiser has permission.");
_;
}
function createEvent(uint _rsvpCost) external { // event creation
require(currentEvent == false, "There is already an ongoing event.");
rsvpCost = _rsvpCost;
currentEvent = true;
}
function cancelEvent() external onlyOwner { // returns all RSVP stakes to guests
for (uint i=0; i<RSVPs.length; i++) {
payable(RSVPs[i]).transfer(rsvpCost); // refunds RSVPers the RSVP cost
}
reset();
}
function guestRSVPing() external payable {
// TO DO -- add rsvp cut off date / time
require(currentEvent == true, "No event to RSVP."); // checks there is an event on
require(RSVPstatus[msg.sender] == false, "You have already RSVP'd."); // checks they havent already RSVP'd
require(rsvpCost >= msg.value, "Wrong amount sent."); // checks guest send enough
RSVPstatus[msg.sender] = true;
RSVPs.push(msg.sender); // adds address to list of RSVPs
}
function guestCheckIn(address _guestAddress) external onlyOwner {
require(currentEvent == true, "No event to check in at."); // checks there is an event on
require(RSVPstatus[_guestAddress], "Guest did not RSVP."); // checks they RSVP'd
require(checkedIn[msg.sender] == false, "Already checked in."); // checks they havent already checked in
checkedIn[_guestAddress] = true;
checkedInAddresses.push(_guestAddress);
}
function payout() external onlyOwner {
if (RSVPs.length != checkedInAddresses.length) { // checks the difference isn't zero
uint potShare = getBalance() / (checkedInAddresses.length);
for (uint i=0; i<checkedInAddresses.length; i++) {
payable(checkedInAddresses[i]).transfer(potShare); // transfers potShare to each checked in address
}
}
reset();
}
function reset() internal { // re-initializes contract
currentEvent = false;
delete RSVPs; // clears list
delete checkedInAddresses; // clears list
}
function getBalance() public view returns(uint) { // returns balance of smart contract
return address(this).balance;
}
}
| checks the difference isn't zero
| if (RSVPs.length != checkedInAddresses.length) { | 989,817 | [
1,
12366,
326,
7114,
5177,
1404,
3634,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
309,
261,
13225,
58,
18124,
18,
2469,
480,
5950,
382,
7148,
18,
2469,
13,
288,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x75A807a667FbcB303f46c0F8Ca45fdfEF8fdC9AC/sources/LiquidationEngine.sol | * @notice Authed function to add contracts that can save SAFEs from liquidation @param saviour SAFE saviour contract to be whitelisted/ | function connectSAFESaviour(address saviour) external isAuthorized {
(bool ok, uint256 collateralAdded, uint256 liquidatorReward) =
SAFESaviourLike(saviour).saveSAFE(address(this), "", address(0));
require(ok, "LiquidationEngine/saviour-not-ok");
require(both(collateralAdded == uint256(-1), liquidatorReward == uint256(-1)), "LiquidationEngine/invalid-amounts");
safeSaviours[saviour] = 1;
emit ConnectSAFESaviour(saviour);
}
| 8,909,340 | [
1,
1730,
329,
445,
358,
527,
20092,
716,
848,
1923,
348,
6799,
6705,
628,
4501,
26595,
367,
225,
7864,
522,
477,
348,
6799,
41,
7864,
522,
477,
6835,
358,
506,
26944,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3077,
5233,
42,
3991,
69,
522,
477,
12,
2867,
7864,
522,
477,
13,
3903,
353,
15341,
288,
203,
3639,
261,
6430,
1529,
16,
2254,
5034,
4508,
2045,
287,
8602,
16,
2254,
5034,
4501,
26595,
639,
17631,
1060,
13,
273,
203,
1850,
348,
6799,
3991,
69,
522,
477,
8804,
12,
13098,
522,
477,
2934,
5688,
22219,
12,
2867,
12,
2211,
3631,
23453,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
601,
16,
315,
48,
18988,
350,
367,
4410,
19,
13098,
522,
477,
17,
902,
17,
601,
8863,
203,
3639,
2583,
12,
18237,
12,
12910,
2045,
287,
8602,
422,
2254,
5034,
19236,
21,
3631,
4501,
26595,
639,
17631,
1060,
422,
2254,
5034,
19236,
21,
13,
3631,
315,
48,
18988,
350,
367,
4410,
19,
5387,
17,
8949,
87,
8863,
203,
3639,
4183,
55,
69,
522,
4390,
63,
13098,
522,
477,
65,
273,
404,
31,
203,
3639,
3626,
8289,
5233,
42,
3991,
69,
522,
477,
12,
13098,
522,
477,
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
] |
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
import "../../DS/DSProxy.sol";
import "../../utils/FlashLoanReceiverBase.sol";
import "../../interfaces/DSProxyInterface.sol";
import "../../exchange/SaverExchangeCore.sol";
import "../../shifter/ShifterRegistry.sol";
/// @title Contract that receives the FL from Aave for Creating loans
contract CompoundCreateReceiver is FlashLoanReceiverBase, SaverExchangeCore {
ILendingPoolAddressesProvider public LENDING_POOL_ADDRESS_PROVIDER = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8);
ShifterRegistry public constant shifterRegistry = ShifterRegistry(0x2E82103bD91053C781aaF39da17aE58ceE39d0ab);
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address payable public constant WALLET_ADDR = 0x322d58b9E75a6918f7e7849AEe0fF09369977e08;
address public constant DISCOUNT_ADDR = 0x1b14E8D511c9A4395425314f849bD737BAF8208F;
// solhint-disable-next-line no-empty-blocks
constructor() public FlashLoanReceiverBase(LENDING_POOL_ADDRESS_PROVIDER) {}
struct CompCreateData {
address payable proxyAddr;
bytes proxyData;
address cCollAddr;
address cDebtAddr;
}
/// @notice Called by Aave when sending back the FL amount
/// @param _reserve The address of the borrowed token
/// @param _amount Amount of FL tokens received
/// @param _fee FL Aave fee
/// @param _params The params that are sent from the original FL caller contract
function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
// Format the call data for DSProxy
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
// If the assets are different
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
// Send amount to DSProxy
sendToProxy(compCreate.proxyAddr, leveragedAsset);
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
// Execute the DSProxy call
DSProxyInterface(compCreate.proxyAddr).execute(compOpenProxy, compCreate.proxyData);
// Repay the loan with the money DSProxy sent back
transferFundsBackToPoolInternal(_reserve, _amount.add(_fee));
// if there is some eth left (0x fee), return it to user
if (address(this).balance > 0) {
// solhint-disable-next-line avoid-tx-origin
tx.origin.transfer(address(this).balance);
}
}
/// @notice Formats function data call so we can call it through DSProxy
/// @param _amount Amount of FL
/// @param _fee Fee of the FL
/// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) {
(
uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x
address[6] memory cAddresses, // cCollAddr, cDebtAddr, srcAddr, destAddr, exchangeAddr, wrapper
bytes memory callData,
address proxy
)
= abi.decode(_params, (uint256[4],address[6],bytes,address));
bytes memory proxyData = abi.encodeWithSignature(
"open(address,address,uint256)",
cAddresses[0], cAddresses[1], (_amount + _fee));
exchangeData = SaverExchangeCore.ExchangeData({
srcAddr: cAddresses[2],
destAddr: cAddresses[3],
srcAmount: numData[0],
destAmount: numData[1],
minPrice: numData[2],
wrapper: cAddresses[5],
exchangeAddr: cAddresses[4],
callData: callData,
price0x: numData[3]
});
compCreate = CompCreateData({
proxyAddr: payable(proxy),
proxyData: proxyData,
cCollAddr: cAddresses[0],
cDebtAddr: cAddresses[1]
});
return (compCreate, exchangeData);
}
/// @notice Send the FL funds received to DSProxy
/// @param _proxy DSProxy address
/// @param _reserve Token address
function sendToProxy(address payable _proxy, address _reserve) internal {
if (_reserve != ETH_ADDRESS) {
ERC20(_reserve).safeTransfer(_proxy, ERC20(_reserve).balanceOf(address(this)));
} else {
_proxy.transfer(address(this).balance);
}
}
function getFee(uint _amount, address _tokenAddr, address _proxy) internal returns (uint feeAmount) {
uint fee = 400;
DSProxy proxy = DSProxy(payable(_proxy));
address user = proxy.owner();
if (Discount(DISCOUNT_ADDR).isCustomFeeSet(user)) {
fee = Discount(DISCOUNT_ADDR).getCustomServiceFee(user);
}
feeAmount = (fee == 0) ? 0 : (_amount / fee);
// fee can't go over 20% of the whole amount
if (feeAmount > (_amount / 5)) {
feeAmount = _amount / 5;
}
if (_tokenAddr == ETH_ADDRESS) {
WALLET_ADDR.transfer(feeAmount);
} else {
ERC20(_tokenAddr).safeTransfer(WALLET_ADDR, feeAmount);
}
}
// solhint-disable-next-line no-empty-blocks
receive() external override(FlashLoanReceiverBase, SaverExchangeCore) payable {}
}
| @notice Called by Aave when sending back the FL amount @param _reserve The address of the borrowed token @param _amount Amount of FL tokens received @param _fee FL Aave fee @param _params The params that are sent from the original FL caller contract Format the call data for DSProxy If the assets are different if there is some eth left (0x fee), return it to user solhint-disable-next-line avoid-tx-origin | function executeOperation(
address _reserve,
uint256 _amount,
uint256 _fee,
bytes calldata _params)
external override {
(CompCreateData memory compCreate, ExchangeData memory exchangeData)
= packFunctionCall(_amount, _fee, _params);
address leveragedAsset = _reserve;
if (compCreate.cCollAddr != compCreate.cDebtAddr) {
(, uint sellAmount) = _sell(exchangeData);
getFee(sellAmount, exchangeData.destAddr, compCreate.proxyAddr);
leveragedAsset = exchangeData.destAddr;
}
address compOpenProxy = shifterRegistry.getAddr("COMP_SHIFTER");
if (address(this).balance > 0) {
tx.origin.transfer(address(this).balance);
}
}
| 7,233,386 | [
1,
8185,
635,
432,
836,
1347,
5431,
1473,
326,
31358,
3844,
225,
389,
455,
6527,
1021,
1758,
434,
326,
29759,
329,
1147,
225,
389,
8949,
16811,
434,
31358,
2430,
5079,
225,
389,
21386,
31358,
432,
836,
14036,
225,
389,
2010,
1021,
859,
716,
854,
3271,
628,
326,
2282,
31358,
4894,
6835,
4077,
326,
745,
501,
364,
8678,
3886,
971,
326,
7176,
854,
3775,
309,
1915,
353,
2690,
13750,
2002,
261,
20,
92,
14036,
3631,
327,
518,
358,
729,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
978,
17,
10012,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
445,
1836,
2988,
12,
203,
3639,
1758,
389,
455,
6527,
16,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
5034,
389,
21386,
16,
203,
3639,
1731,
745,
892,
389,
2010,
13,
203,
565,
3903,
3849,
288,
203,
3639,
261,
2945,
1684,
751,
3778,
1161,
1684,
16,
18903,
751,
3778,
7829,
751,
13,
203,
4766,
273,
2298,
2083,
1477,
24899,
8949,
16,
389,
21386,
16,
389,
2010,
1769,
203,
203,
203,
3639,
1758,
884,
502,
11349,
6672,
273,
389,
455,
6527,
31,
203,
203,
3639,
309,
261,
2919,
1684,
18,
71,
13535,
3178,
480,
1161,
1684,
18,
71,
758,
23602,
3178,
13,
288,
203,
5411,
261,
16,
2254,
357,
80,
6275,
13,
273,
389,
87,
1165,
12,
16641,
751,
1769,
203,
5411,
2812,
1340,
12,
87,
1165,
6275,
16,
7829,
751,
18,
10488,
3178,
16,
1161,
1684,
18,
5656,
3178,
1769,
203,
203,
5411,
884,
502,
11349,
6672,
273,
7829,
751,
18,
10488,
3178,
31,
203,
3639,
289,
203,
203,
203,
3639,
1758,
1161,
3678,
3886,
273,
699,
430,
387,
4243,
18,
588,
3178,
2932,
10057,
67,
2664,
5501,
2560,
8863,
203,
203,
203,
203,
3639,
309,
261,
2867,
12,
2211,
2934,
12296,
405,
374,
13,
288,
203,
5411,
2229,
18,
10012,
18,
13866,
12,
2867,
12,
2211,
2934,
12296,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract NaiveReceiverAttack {
address immutable public pool;
constructor(address _pool) {
pool = _pool;
}
// Unsafe function that uses .call() for convenience. This function really should be reentrancy guarded but its just
// a helper to exploit the NaiveReceiverLenderPool so I take no precautions.
function flashLoanMultiple(address borrower) external {
// This assumes that the borrower has exactly 10 ETH since each floash loan sends 1 ETH to the pool address.
for (uint256 i; i < 10;) {
(bool success, ) = pool.call(
abi.encodeWithSignature(
"flashLoan(address,uint256)",
borrower,
1 // Amount to borrow does not matter, as the flash loan fee is fixed.
)
);
require(success);
unchecked {
i++;
}
}
}
}
| Unsafe function that uses .call() for convenience. This function really should be reentrancy guarded but its just a helper to exploit the NaiveReceiverLenderPool so I take no precautions. This assumes that the borrower has exactly 10 ETH since each floash loan sends 1 ETH to the pool address. | function flashLoanMultiple(address borrower) external {
for (uint256 i; i < 10;) {
(bool success, ) = pool.call(
abi.encodeWithSignature(
"flashLoan(address,uint256)",
borrower,
)
);
require(success);
unchecked {
i++;
}
}
}
| 12,595,215 | [
1,
23912,
445,
716,
4692,
263,
1991,
1435,
364,
13553,
18,
1220,
445,
8654,
1410,
506,
283,
8230,
12514,
3058,
17212,
1496,
2097,
2537,
279,
4222,
358,
15233,
305,
326,
16350,
688,
12952,
48,
2345,
2864,
1427,
467,
4862,
1158,
675,
5353,
6170,
18,
1220,
13041,
716,
326,
29759,
264,
711,
8950,
1728,
512,
2455,
3241,
1517,
20802,
961,
28183,
9573,
404,
512,
2455,
358,
326,
2845,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
9563,
1504,
304,
8438,
12,
2867,
29759,
264,
13,
3903,
288,
203,
3639,
364,
261,
11890,
5034,
277,
31,
277,
411,
1728,
30943,
288,
203,
5411,
261,
6430,
2216,
16,
262,
273,
2845,
18,
1991,
12,
203,
7734,
24126,
18,
3015,
1190,
5374,
12,
203,
10792,
315,
13440,
1504,
304,
12,
2867,
16,
11890,
5034,
2225,
16,
203,
10792,
29759,
264,
16,
203,
7734,
262,
203,
5411,
11272,
203,
5411,
2583,
12,
4768,
1769,
203,
5411,
22893,
288,
203,
7734,
277,
9904,
31,
203,
5411,
289,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
contract Ownable {
address public owner;
event NewOwner (address indexed owner);
function Ownable () public {
owner = msg.sender;
}
modifier onlyOwner () {
if (owner != msg.sender) revert();
_;
}
function setOwner (address candidate) public onlyOwner {
if (candidate == address(0)) revert();
owner = candidate;
emit NewOwner(owner);
}
}
contract TokenAware is Ownable {
function withdrawToken (address addressOfToken, uint256 amount) onlyOwner public returns (bool) {
bytes4 hashOfTransfer = bytes4(keccak256('transfer(address,uint256)'));
return addressOfToken.call(hashOfTransfer, owner, amount);
}
}
contract Destructible is TokenAware {
function kill () public onlyOwner {
selfdestruct(owner);
}
}
contract Pausable is Destructible {
bool public paused;
event NewStatus (bool isPaused);
modifier whenNotPaused () {
if (paused) revert();
_;
}
modifier whenPaused () {
if (!paused) revert();
_;
}
function setStatus (bool isPaused) public onlyOwner {
paused = isPaused;
emit NewStatus(isPaused);
}
}
contract Operable is Pausable {
address[] public operators;
event NewOperator(address indexed operator);
event RemoveOperator(address indexed operator);
function Operable (address[] newOperators) public {
operators = newOperators;
}
modifier restricted () {
if (owner != msg.sender &&
!containsOperator(msg.sender)) revert();
_;
}
modifier onlyOperator () {
if (!containsOperator(msg.sender)) revert();
_;
}
function containsOperator (address candidate) public constant returns (bool) {
for (uint256 x = 0; x < operators.length; x++) {
address operator = operators[x];
if (candidate == operator) {
return true;
}
}
return false;
}
function indexOfOperator (address candidate) public constant returns (int256) {
for (uint256 x = 0; x < operators.length; x++) {
address operator = operators[x];
if (candidate == operator) {
return int256(x);
}
}
return -1;
}
function addOperator (address candidate) public onlyOwner {
if (candidate == address(0) || containsOperator(candidate)) revert();
operators.push(candidate);
emit NewOperator(candidate);
}
function removeOperator (address operator) public onlyOwner {
int256 indexOf = indexOfOperator(operator);
if (indexOf < 0) revert();
// overwrite operator with last operator in the array
if (uint256(indexOf) != operators.length - 1) {
address lastOperator = operators[operators.length - 1];
operators[uint256(indexOf)] = lastOperator;
}
// delete the last element
delete operators[operators.length - 1];
emit RemoveOperator(operator);
}
}
contract EtherShuffle is Operable {
uint256 public nextGameId = 1;
uint256 public lowestGameWithoutQuorum = 1;
uint256[5] public distributions = [300000000000000000, // 30%
250000000000000000,
225000000000000000,
212500000000000000,
0];
// 12500000000000000 == 1.25%
uint8 public constant countOfParticipants = 5;
uint256 public gamePrice = 100 finney;
mapping (uint256 => Shuffle) public games;
mapping (address => uint256[]) public gamesByPlayer;
mapping (uint256 => uint256) public gamesWithoutQuorum;
mapping (address => uint256) public balances;
struct Shuffle {
uint256 id;
address[] players;
bytes32 hash;
uint8[5] result;
bytes32 secret;
uint256 value;
}
event NewGame (uint256 indexed gameId);
event NewHash (uint256 indexed gameId);
event NewReveal (uint256 indexed gameId);
event NewPrice (uint256 price);
event NewDistribution (uint256[5]);
event Quorum (uint256 indexed gameId);
function EtherShuffle (address[] operators)
Operable(operators) public {
}
modifier onlyExternalAccount () {
uint size;
address addr = msg.sender;
assembly { size := extcodesize(addr) }
if (size > 0) revert();
_;
}
// send 0 ETH to withdraw, otherwise send enough to play
function () public payable {
if (msg.value == 0) {
withdrawTo(msg.sender);
} else {
play();
}
}
function play () public payable whenNotPaused onlyExternalAccount {
if (msg.value < gamePrice) revert();
joinGames(msg.sender, msg.value);
}
function playFromBalance () public whenNotPaused onlyExternalAccount {
uint256 balanceOf = balances[msg.sender];
if (balanceOf < gamePrice) revert();
balances[msg.sender] = 0;
joinGames(msg.sender, balanceOf);
}
function joinGames (address player, uint256 value) private {
while (value >= gamePrice) {
uint256 id = findAvailableGame(player);
Shuffle storage game = games[id];
value -= gamePrice;
joinGame(game, player, gamePrice);
}
balances[player] += value;
if (balances[player] < value) revert();
}
function joinGame (Shuffle storage game, address player, uint256 value) private {
if (game.id == 0) revert();
if (value != gamePrice) revert();
game.value += gamePrice;
if (game.value < gamePrice) revert();
game.players.push(player);
gamesByPlayer[player].push(game.id);
if (game.players.length == countOfParticipants) {
delete gamesWithoutQuorum[game.id];
lowestGameWithoutQuorum++;
emit Quorum(game.id);
}
if (game.players.length > countOfParticipants) revert();
}
function findAvailableGame (address player) private returns (uint256) {
for (uint256 x = lowestGameWithoutQuorum; x < nextGameId; x++) {
Shuffle storage game = games[x];
// games which have met quorum are removed from this mapping
if (game.id == 0) continue;
if (!contains(game, player)) {
return game.id;
}
}
// if a sender gets here, they've joined all available games,
// create a new one
return newGame();
}
function newGame () private returns (uint256) {
uint256 gameId = nextGameId;
nextGameId++;
Shuffle storage game = games[gameId];
// ensure this is a real uninitialized game
if (game.id != 0) revert();
game.id = gameId;
gamesWithoutQuorum[gameId] = gameId;
emit NewGame(gameId);
return gameId;
}
function gamesOf (address player) public constant returns (uint256[]) {
return gamesByPlayer[player];
}
function balanceOf (address player) public constant returns (uint256) {
return balances[player];
}
function getPlayers (uint256 gameId) public constant returns (address[]) {
Shuffle storage game = games[gameId];
return game.players;
}
function hasHash (uint256 gameId) public constant returns (bool) {
Shuffle storage game = games[gameId];
return game.hash != bytes32(0);
}
function getHash (uint256 gameId) public constant returns (bytes32) {
Shuffle storage game = games[gameId];
return game.hash;
}
function getResult (uint256 gameId) public constant returns (uint8[5]) {
Shuffle storage game = games[gameId];
return game.result;
}
function hasSecret (uint256 gameId) public constant returns (bool) {
Shuffle storage game = games[gameId];
return game.secret != bytes32(0);
}
function getSecret (uint256 gameId) public constant returns (bytes32) {
Shuffle storage game = games[gameId];
return game.secret;
}
function getValue (uint256 gameId) public constant returns (uint256) {
Shuffle storage game = games[gameId];
return game.value;
}
function setHash (uint256 gameId, bytes32 hash) public whenNotPaused restricted {
Shuffle storage game = games[gameId];
if (game.id == 0) revert();
if (game.hash != bytes32(0)) revert();
game.hash = hash;
emit NewHash(game.id);
}
function reveal (uint256 gameId, uint8[5] result, bytes32 secret) public whenNotPaused restricted {
Shuffle storage game = games[gameId];
if (game.id == 0) revert();
if (game.players.length < uint256(countOfParticipants)) revert();
if (game.hash == bytes32(0)) revert();
if (game.secret != bytes32(0)) revert();
bytes32 hash = keccak256(result, secret);
if (game.hash != hash) revert();
game.secret = secret;
game.result = result;
disburse(game);
emit NewReveal(gameId);
}
function disburse (Shuffle storage game) private restricted {
if (game.players.length != countOfParticipants) revert();
uint256 totalValue = game.value;
for (uint8 x = 0; x < game.result.length; x++) {
uint256 indexOfDistribution = game.result[x];
address player = game.players[x];
uint256 playerDistribution = distributions[indexOfDistribution];
uint256 disbursement = totalValue * playerDistribution / (1 ether);
uint256 playerBalance = balances[player];
game.value -= disbursement;
playerBalance += disbursement;
if (playerBalance < disbursement) revert();
balances[player] = playerBalance;
}
balances[owner] += game.value;
game.value = 0;
}
function setPrice (uint256 price) public onlyOwner {
gamePrice = price;
emit NewPrice(price);
}
function setDistribution (uint256[5] winnings) public onlyOwner {
distributions = winnings;
emit NewDistribution(winnings);
}
// anyone can withdraw on behalf of someone (when the player lacks the gas, for instance)
function withdrawToMany (address[] players) public {
for (uint8 x = 0; x < players.length; x++) {
address player = players[x];
withdrawTo(player);
}
}
function withdraw () public {
withdrawTo(msg.sender);
}
function withdrawTo (address player) public {
uint256 playerBalance = balances[player];
if (playerBalance > 0) {
balances[player] = 0;
player.transfer(playerBalance);
}
}
function contains (uint256 gameId, address candidate) public constant returns (bool) {
Shuffle storage game = games[gameId];
return contains(game, candidate);
}
function contains (Shuffle storage game, address candidate) private constant returns (bool) {
for (uint256 x = 0; x < game.players.length; x++) {
address player = game.players[x];
if (candidate == player) {
return true;
}
}
return false;
}
function createHash (uint8[5] result, bytes32 secret) public pure returns (bytes32) {
bytes32 hash = keccak256(result, secret);
return hash;
}
function verify (bytes32 hash, uint8[5] result, bytes32 secret) public pure returns (bool) {
return hash == createHash(result, secret);
}
function verifyGame (uint256 gameId) public constant returns (bool) {
Shuffle storage game = games[gameId];
return verify(game.hash, game.result, game.secret);
}
function verifySignature (address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) public pure returns (bool) {
bytes memory prefix = '\x19Ethereum Signed Message:\n32';
bytes32 prefixedHash = keccak256(prefix, hash);
return ecrecover(prefixedHash, v, r, s) == signer;
}
function getNextGameId () public constant returns (uint256) {
return nextGameId;
}
function getLowestGameWithoutQuorum () public constant returns (uint256) {
return lowestGameWithoutQuorum;
}
} | games which have met quorum are removed from this mapping | function findAvailableGame (address player) private returns (uint256) {
for (uint256 x = lowestGameWithoutQuorum; x < nextGameId; x++) {
Shuffle storage game = games[x];
if (game.id == 0) continue;
if (!contains(game, player)) {
return game.id;
}
}
}
| 12,894,958 | [
1,
75,
753,
1492,
1240,
5100,
31854,
854,
3723,
628,
333,
2874,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1104,
5268,
12496,
261,
2867,
7291,
13,
3238,
1135,
261,
11890,
5034,
13,
288,
203,
565,
364,
261,
11890,
5034,
619,
273,
11981,
12496,
8073,
31488,
31,
619,
411,
1024,
12496,
548,
31,
619,
27245,
288,
203,
1377,
2638,
10148,
2502,
7920,
273,
28422,
63,
92,
15533,
203,
203,
1377,
309,
261,
13957,
18,
350,
422,
374,
13,
1324,
31,
203,
203,
1377,
309,
16051,
12298,
12,
13957,
16,
7291,
3719,
288,
203,
3639,
327,
7920,
18,
350,
31,
203,
1377,
289,
203,
565,
289,
203,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.