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 |
---|---|---|---|---|---|---|
// CryptoRabbit Source code
pragma solidity ^0.4.20;
/**
*
* @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
* @author cuilichen
*/
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint total);
function balanceOf(address _owner) public view returns (uint balance);
function ownerOf(uint _tokenId) external view returns (address owner);
function approve(address _to, uint _tokenId) external;
function transfer(address _to, uint _tokenId) external;
function transferFrom(address _from, address _to, uint _tokenId) external;
// Events
event Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
/// @title A base contract to control ownership
/// @author cuilichen
contract OwnerBase {
// The addresses of the accounts that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// constructor
function OwnerBase() public {
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCFO The address of the new COO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCOO whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCOO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/// @dev check wether target address is a contract or not
function isNotContract(address addr) internal view returns (bool) {
uint size = 0;
assembly {
size := extcodesize(addr)
}
return size == 0;
}
}
/**
*
* @title Interface for contracts conforming to fighters camp
* @author cuilichen
*/
contract FighterCamp {
//
function isCamp() public pure returns (bool);
// Required methods
function getFighter(uint _tokenId) external view returns (uint32);
}
/// @title Base contract for CryptoRabbit. Holds all common structs, events and base variables.
/// @author cuilichen
/// @dev See the RabbitCore contract documentation to understand how the various contract facets are arranged.
contract RabbitBase is ERC721, OwnerBase, FighterCamp {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new rabbit comes into existence.
event Birth(address owner, uint rabbitId, uint32 star, uint32 explosive, uint32 endurance, uint32 nimble, uint64 genes, uint8 isBox);
/*** DATA TYPES ***/
struct RabbitData {
//genes for rabbit
uint64 genes;
//
uint32 star;
//
uint32 explosive;
//
uint32 endurance;
//
uint32 nimble;
//birth time
uint64 birthTime;
}
/// @dev An array containing the Rabbit struct for all rabbits in existence. The ID
/// of each rabbit is actually an index into this array.
RabbitData[] rabbits;
/// @dev A mapping from rabbit IDs to the address that owns them.
mapping (uint => address) rabbitToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint) howManyDoYouHave;
/// @dev A mapping from RabbitIDs to an address that has been approved to call
/// transfeFrom(). Each Rabbit can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint => address) public rabbitToApproved;
/// @dev Assigns ownership of a specific Rabbit to an address.
function _transItem(address _from, address _to, uint _tokenId) internal {
// Since the number of rabbits is capped to 2^32 we can't overflow this
howManyDoYouHave[_to]++;
// transfer ownership
rabbitToOwner[_tokenId] = _to;
// When creating new rabbits _from is 0x0, but we can't account that address.
if (_from != address(0)) {
howManyDoYouHave[_from]--;
}
// clear any previously approved ownership exchange
delete rabbitToApproved[_tokenId];
// Emit the transfer event.
if (_tokenId > 0) {
emit Transfer(_from, _to, _tokenId);
}
}
/// @dev An internal method that creates a new rabbit and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
function _createRabbit(
uint _star,
uint _explosive,
uint _endurance,
uint _nimble,
uint _genes,
address _owner,
uint8 isBox
)
internal
returns (uint)
{
require(_star >= 1 && _star <= 5);
RabbitData memory _tmpRbt = RabbitData({
genes: uint64(_genes),
star: uint32(_star),
explosive: uint32(_explosive),
endurance: uint32(_endurance),
nimble: uint32(_nimble),
birthTime: uint64(now)
});
uint newRabbitID = rabbits.push(_tmpRbt) - 1;
/* */
// emit the birth event
emit Birth(
_owner,
newRabbitID,
_tmpRbt.star,
_tmpRbt.explosive,
_tmpRbt.endurance,
_tmpRbt.nimble,
_tmpRbt.genes,
isBox
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
if (_owner != address(0)){
_transItem(0, _owner, newRabbitID);
} else {
_transItem(0, ceoAddress, newRabbitID);
}
return newRabbitID;
}
/// @notice Returns all the relevant information about a specific rabbit.
/// @param _tokenId The ID of the rabbit of interest.
function getRabbit(uint _tokenId) external view returns (
uint32 outStar,
uint32 outExplosive,
uint32 outEndurance,
uint32 outNimble,
uint64 outGenes,
uint64 outBirthTime
) {
RabbitData storage rbt = rabbits[_tokenId];
outStar = rbt.star;
outExplosive = rbt.explosive;
outEndurance = rbt.endurance;
outNimble = rbt.nimble;
outGenes = rbt.genes;
outBirthTime = rbt.birthTime;
}
function isCamp() public pure returns (bool){
return true;
}
/// @dev An external method that get infomation of the fighter
/// @param _tokenId The ID of the fighter.
function getFighter(uint _tokenId) external view returns (uint32) {
RabbitData storage rbt = rabbits[_tokenId];
uint32 strength = uint32(rbt.explosive + rbt.endurance + rbt.nimble);
return strength;
}
}
/// @title The facet of the CryptoRabbit core contract that manages ownership, ERC-721 (draft) compliant.
/// @author cuilichen
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the RabbitCore contract documentation to understand how the various contract facets are arranged.
contract RabbitOwnership is RabbitBase {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name;
string public symbol;
//identify this is ERC721
function isERC721() public pure returns (bool) {
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Rabbit.
/// @param _owner the address we are validating against.
/// @param _tokenId rabbit id, only valid when > 0
function _owns(address _owner, uint _tokenId) internal view returns (bool) {
return rabbitToOwner[_tokenId] == _owner;
}
/// @dev Checks if a given address currently has transferApproval for a particular Rabbit.
/// @param _claimant the address we are confirming rabbit is approved for.
/// @param _tokenId rabbit id, only valid when > 0
function _approvedFor(address _claimant, uint _tokenId) internal view returns (bool) {
return rabbitToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transfeFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transfeFrom() are used together for putting rabbits on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint _tokenId, address _to) internal {
rabbitToApproved[_tokenId] = _to;
}
/// @notice Returns the number of rabbits owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint count) {
return howManyDoYouHave[_owner];
}
/// @notice Transfers a Rabbit to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoRabbit specifically) or your Rabbit may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Rabbit to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own rabbit.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transItem(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Rabbit via
/// transfeFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Rabbit that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId)); // Only an owner can grant transfer approval.
require(msg.sender != _to); // can not approve to itself;
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Rabbit owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Rabbit to be transfered.
/// @param _to The address that should take ownership of the Rabbit. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Rabbit to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
//
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transItem(_from, _to, _tokenId);
}
/// @notice Returns the total number of rabbits currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return rabbits.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Rabbit.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _tokenId)
external
view
returns (address owner)
{
owner = rabbitToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Rabbit IDs assigned to an address.
/// @param _owner The owner whose rabbits we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Rabbit array looking for rabbits belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint[] ownerTokens) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
uint totalCats = totalSupply();
uint resultIndex = 0;
// We count on the fact that all rabbits have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint rabbitId;
for (rabbitId = 1; rabbitId <= totalCats; rabbitId++) {
if (rabbitToOwner[rabbitId] == _owner) {
result[resultIndex] = rabbitId;
resultIndex++;
}
}
return result;
}
}
}
/// @title all functions related to creating rabbits and sell rabbits
contract RabbitMinting is RabbitOwnership {
// Price (in wei) for star5 rabbit
uint public priceStar5Now = 1 ether;
// Price (in wei) for star4 rabbit
uint public priceStar4 = 100 finney;
// Price (in wei) for star3 rabbit
uint public priceStar3 = 5 finney;
uint private priceStar5Min = 1 ether;
uint private priceStar5Add = 2 finney;
//rabbit box1
uint public priceBox1 = 10 finney;
uint public box1Star5 = 50;
uint public box1Star4 = 500;
//rabbit box2
uint public priceBox2 = 100 finney;
uint public box2Star5 = 500;
// Limits the number of star5 rabbits can ever create.
uint public constant LIMIT_STAR5 = 2000;
// Limits the number of star4 rabbits can ever create.
uint public constant LIMIT_STAR4 = 20000;
// Limits the number of rabbits the contract owner can ever create.
uint public constant LIMIT_PROMO = 5000;
// Counts the number of rabbits of star 5
uint public CREATED_STAR5;
// Counts the number of rabbits of star 4
uint public CREATED_STAR4;
// Counts the number of rabbits the contract owner has created.
uint public CREATED_PROMO;
//an secret key used for random
uint private secretKey = 392828872;
//box is on sale
bool private box1OnSale = true;
//box is on sale
bool private box2OnSale = true;
//record any task id for updating datas;
mapping(uint => uint8) usedSignId;
/// @dev set base infomation by coo
function setBaseInfo(uint val, bool _onSale1, bool _onSale2) external onlyCOO {
secretKey = val;
box1OnSale = _onSale1;
box2OnSale = _onSale2;
}
/// @dev we can create promo rabbits, up to a limit. Only callable by COO
function createPromoRabbit(uint _star, address _owner) whenNotPaused external onlyCOO {
require (_owner != address(0));
require(CREATED_PROMO < LIMIT_PROMO);
if (_star == 5){
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (_star == 4){
require(CREATED_STAR4 < LIMIT_STAR4);
}
CREATED_PROMO++;
_createRabbitInGrade(_star, _owner, 0);
}
/// @dev create a rabbit with grade, and set its owner.
function _createRabbitInGrade(uint _star, address _owner, uint8 isBox) internal {
uint _genes = uint(keccak256(uint(_owner) + secretKey + rabbits.length));
uint _explosive = 50;
uint _endurance = 50;
uint _nimble = 50;
if (_star < 5) {
uint tmp = _genes;
tmp = uint(keccak256(tmp));
_explosive = 1 + 10 * (_star - 1) + tmp % 10;
tmp = uint(keccak256(tmp));
_endurance = 1 + 10 * (_star - 1) + tmp % 10;
tmp = uint(keccak256(tmp));
_nimble = 1 + 10 * (_star - 1) + tmp % 10;
}
uint64 _geneShort = uint64(_genes);
if (_star == 5){
CREATED_STAR5++;
priceStar5Now = priceStar5Min + priceStar5Add * CREATED_STAR5;
_geneShort = uint64(_geneShort - _geneShort % 2000 + CREATED_STAR5);
} else if (_star == 4){
CREATED_STAR4++;
}
_createRabbit(
_star,
_explosive,
_endurance,
_nimble,
_geneShort,
_owner,
isBox);
}
/// @notice customer buy a rabbit
/// @param _star the star of the rabbit to buy
function buyOneRabbit(uint _star) external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
uint tmpPrice = 0;
if (_star == 5){
tmpPrice = priceStar5Now;
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (_star == 4){
tmpPrice = priceStar4;
require(CREATED_STAR4 < LIMIT_STAR4);
} else if (_star == 3){
tmpPrice = priceStar3;
} else {
revert();
}
require(msg.value >= tmpPrice);
_createRabbitInGrade(_star, msg.sender, 0);
// Return the funds.
uint fundsExcess = msg.value - tmpPrice;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
/// @notice customer buy a box
function buyBox1() external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
require(box1OnSale);
require(msg.value >= priceBox1);
uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length));
tempVal = tempVal % 10000;
uint _star = 3; //default
if (tempVal <= box1Star5){
_star = 5;
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (tempVal <= box1Star5 + box1Star4){
_star = 4;
require(CREATED_STAR4 < LIMIT_STAR4);
}
_createRabbitInGrade(_star, msg.sender, 2);
// Return the funds.
uint fundsExcess = msg.value - priceBox1;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
/// @notice customer buy a box
function buyBox2() external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
require(box2OnSale);
require(msg.value >= priceBox2);
uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length));
tempVal = tempVal % 10000;
uint _star = 4; //default
if (tempVal <= box2Star5){
_star = 5;
require(CREATED_STAR5 < LIMIT_STAR5);
} else {
require(CREATED_STAR4 < LIMIT_STAR4);
}
_createRabbitInGrade(_star, msg.sender, 3);
// Return the funds.
uint fundsExcess = msg.value - priceBox2;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
}
/// @title all functions related to creating rabbits and sell rabbits
contract RabbitAuction is RabbitMinting {
//events about auctions
event AuctionCreated(uint tokenId, uint startingPrice, uint endingPrice, uint duration, uint startTime, uint32 explosive, uint32 endurance, uint32 nimble, uint32 star);
event AuctionSuccessful(uint tokenId, uint totalPrice, address winner);
event AuctionCancelled(uint tokenId);
event UpdateComplete(address account, uint tokenId);
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
uint64 startedAt;
}
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint public masterCut = 200;
// Map from token ID to their corresponding auction.
mapping (uint => Auction) tokenIdToAuction;
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
function createAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration
)
external whenNotPaused
{
require(isNotContract(msg.sender));
require(_endingPrice >= 1 finney);
require(_startingPrice >= _endingPrice);
require(_duration <= 100 days);
require(_owns(msg.sender, _tokenId));
//assigning the ownship to this contract,
_transItem(msg.sender, this, _tokenId);
Auction memory auction = Auction(
msg.sender,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuctionData(uint _tokenId) external view returns (
address seller,
uint startingPrice,
uint endingPrice,
uint duration,
uint startedAt,
uint currentPrice
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
seller = auction.seller;
startingPrice = auction.startingPrice;
endingPrice = auction.endingPrice;
duration = auction.duration;
startedAt = auction.startedAt;
currentPrice = _calcCurrentPrice(auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint _tokenId) external payable whenNotPaused {
require(isNotContract(msg.sender));
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
// Check that the bid is greater than or equal to the current price
uint price = _calcCurrentPrice(auction);
require(msg.value >= price);
// Grab a reference to the seller before the auction struct gets deleted.
address seller = auction.seller;
//
require(_owns(this, _tokenId));
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy endurance.
delete tokenIdToAuction[_tokenId];
if (price > 0) {
// Calculate the auctioneer's cut.
uint auctioneerCut = price * masterCut / 10000;
uint sellerProceeds = price - auctioneerCut;
require(sellerProceeds <= price);
// Doing a transfer() after removing the auction
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid.
uint bidExcess = msg.value - price;
// Return the funds.
if (bidExcess >= 1 finney) {
msg.sender.transfer(bidExcess);
}
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
//give goods to bidder.
_transItem(this, msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint _tokenId) external whenNotPaused {
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionByMaster(uint _tokenId)
external onlyCOO whenPaused
{
_cancelAuction(_tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires an event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
RabbitData storage rdata = rabbits[_tokenId];
emit AuctionCreated(
uint(_tokenId),
uint(_auction.startingPrice),
uint(_auction.endingPrice),
uint(_auction.duration),
uint(_auction.startedAt),
uint32(rdata.explosive),
uint32(rdata.endurance),
uint32(rdata.nimble),
uint32(rdata.star)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint _tokenId) internal {
Auction storage auction = tokenIdToAuction[_tokenId];
_transItem(this, auction.seller, _tokenId);
delete tokenIdToAuction[_tokenId];
emit AuctionCancelled(_tokenId);
}
/// @dev Returns current price of an NFT on auction.
function _calcCurrentPrice(Auction storage _auction)
internal
view
returns (uint outPrice)
{
int256 duration = _auction.duration;
int256 price0 = _auction.startingPrice;
int256 price2 = _auction.endingPrice;
require(duration > 0);
int256 secondsPassed = int256(now) - int256(_auction.startedAt);
require(secondsPassed >= 0);
if (secondsPassed < _auction.duration) {
int256 priceChanged = (price2 - price0) * secondsPassed / duration;
int256 currentPrice = price0 + priceChanged;
outPrice = uint(currentPrice);
} else {
outPrice = _auction.endingPrice;
}
}
/// @dev tranfer token to the target, in case of some error occured.
/// Only the coo may do this.
/// @param _to The target address.
/// @param _to The id of the token.
function transferOnError(address _to, uint _tokenId) external onlyCOO {
require(_owns(this, _tokenId));
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt == 0);
_transItem(this, _to, _tokenId);
}
/// @dev allow the user to draw a rabbit, with a signed message from coo
function getFreeRabbit(uint32 _star, uint _taskId, uint8 v, bytes32 r, bytes32 s) external {
require(usedSignId[_taskId] == 0);
uint[2] memory arr = [_star, _taskId];
string memory text = uint2ToStr(arr);
address signer = verify(text, v, r, s);
require(signer == cooAddress);
_createRabbitInGrade(_star, msg.sender, 4);
usedSignId[_taskId] = 1;
}
/// @dev allow any user to set rabbit data, with a signed message from coo
function setRabbitData(
uint _tokenId,
uint32 _explosive,
uint32 _endurance,
uint32 _nimble,
uint _taskId,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(usedSignId[_taskId] == 0);
Auction storage auction = tokenIdToAuction[_tokenId];
require (auction.startedAt == 0);
uint[5] memory arr = [_tokenId, _explosive, _endurance, _nimble, _taskId];
string memory text = uint5ToStr(arr);
address signer = verify(text, v, r, s);
require(signer == cooAddress);
RabbitData storage rdata = rabbits[_tokenId];
rdata.explosive = _explosive;
rdata.endurance = _endurance;
rdata.nimble = _nimble;
rabbits[_tokenId] = rdata;
usedSignId[_taskId] = 1;
emit UpdateComplete(msg.sender, _tokenId);
}
/// @dev werify wether the message is form coo or not.
function verify(string text, uint8 v, bytes32 r, bytes32 s) public pure returns (address) {
bytes32 hash = keccak256(text);
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, hash);
address tmp = ecrecover(prefixedHash, v, r, s);
return tmp;
}
/// @dev create an string according to the array
function uint2ToStr(uint[2] arr) internal pure returns (string){
uint length = 0;
uint i = 0;
uint val = 0;
for(; i < arr.length; i++){
val = arr[i];
while(val >= 10) {
length += 1;
val = val / 10;
}
length += 1;//for single
length += 1;//for comma
}
length -= 1;//remove last comma
//copy char to bytes
bytes memory bstr = new bytes(length);
uint k = length - 1;
int j = int(arr.length - 1);
while (j >= 0) {
val = arr[uint(j)];
if (val == 0) {
bstr[k] = byte(48);
if (k > 0) {
k--;
}
} else {
while (val != 0){
bstr[k] = byte(48 + val % 10);
val /= 10;
if (k > 0) {
k--;
}
}
}
if (j > 0) { //add comma
assert(k > 0);
bstr[k] = byte(44);
k--;
}
j--;
}
return string(bstr);
}
/// @dev create an string according to the array
function uint5ToStr(uint[5] arr) internal pure returns (string){
uint length = 0;
uint i = 0;
uint val = 0;
for(; i < arr.length; i++){
val = arr[i];
while(val >= 10) {
length += 1;
val = val / 10;
}
length += 1;//for single
length += 1;//for comma
}
length -= 1;//remove last comma
//copy char to bytes
bytes memory bstr = new bytes(length);
uint k = length - 1;
int j = int(arr.length - 1);
while (j >= 0) {
val = arr[uint(j)];
if (val == 0) {
bstr[k] = byte(48);
if (k > 0) {
k--;
}
} else {
while (val != 0){
bstr[k] = byte(48 + val % 10);
val /= 10;
if (k > 0) {
k--;
}
}
}
if (j > 0) { //add comma
assert(k > 0);
bstr[k] = byte(44);
k--;
}
j--;
}
return string(bstr);
}
}
/// @title CryptoRabbit: Collectible, oh-so-adorable rabbits on the Ethereum blockchain.
/// @author cuilichen
/// @dev The main CryptoRabbit contract, keeps track of rabbits so they don't wander around and get lost.
/// This is the main CryptoRabbit contract. In order to keep our code seperated into logical sections.
contract RabbitCore is RabbitAuction {
event ContractUpgrade(address newContract);
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoRabbit smart contract instance.
function RabbitCore(string _name, string _symbol) public {
name = _name;
symbol = _symbol;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
//first rabbit in this world
_createRabbit(5, 50, 50, 50, 1, msg.sender, 0);
}
/// @dev Used to mark the smart contract as upgraded.
/// @param _v2Address new address
function upgradeContract(address _v2Address) external onlyCOO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCOO {
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CEO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
address tmp = address(this);
cfoAddress.transfer(tmp.balance);
}
} | @dev Cancels an auction when the contract is paused. Only the owner may do this, and NFTs are returned to the seller. This should only be used in emergencies. @param _tokenId - ID of the NFT on auction to cancel. | function cancelAuctionByMaster(uint _tokenId)
external onlyCOO whenPaused
{
_cancelAuction(_tokenId);
}
| 2,515,423 | [
1,
6691,
87,
392,
279,
4062,
1347,
326,
6835,
353,
17781,
18,
225,
5098,
326,
3410,
2026,
741,
333,
16,
471,
423,
4464,
87,
854,
2106,
358,
225,
326,
29804,
18,
1220,
1410,
1338,
506,
1399,
316,
801,
18639,
3209,
18,
225,
389,
2316,
548,
300,
1599,
434,
326,
423,
4464,
603,
279,
4062,
358,
3755,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3755,
37,
4062,
858,
7786,
12,
11890,
389,
2316,
548,
13,
203,
3639,
3903,
1338,
3865,
51,
1347,
28590,
203,
565,
288,
203,
3639,
389,
10996,
37,
4062,
24899,
2316,
548,
1769,
203,
565,
289,
203,
202,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2019-12-03
*/
pragma solidity 0.5.13;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
// 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;
}
}
/**
* @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 {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public 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 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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
contract GlobalsAndUtility is ERC20 {
/* XfLobbyEnter (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint96 rawAmount --> data0 [135: 40]
address indexed referrerAddr
*/
event XfLobbyEnter(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* XfLobbyExit (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed memberAddr
uint256 indexed entryId
uint72 xfAmount --> data0 [111: 40]
address indexed referrerAddr
*/
event XfLobbyExit(
uint256 data0,
address indexed memberAddr,
uint256 indexed entryId,
address indexed referrerAddr
);
/* DailyDataUpdate (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint16 beginDay --> data0 [ 55: 40]
uint16 endDay --> data0 [ 71: 56]
bool isAutoUpdate --> data0 [ 79: 72]
address indexed updaterAddr
*/
event DailyDataUpdate(
uint256 data0,
address indexed updaterAddr
);
/* Claim (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 indexed btcAddr
uint56 rawSatoshis --> data0 [ 95: 40]
uint56 adjSatoshis --> data0 [151: 96]
address indexed claimToAddr
uint8 claimFlags --> data0 [159:152]
uint72 claimedHearts --> data0 [231:160]
address indexed referrerAddr
address senderAddr --> data1 [159: 0]
*/
event Claim(
uint256 data0,
uint256 data1,
bytes20 indexed btcAddr,
address indexed claimToAddr,
address indexed referrerAddr
);
/* ClaimAssist (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
bytes20 btcAddr --> data0 [199: 40]
uint56 rawSatoshis --> data0 [255:200]
uint56 adjSatoshis --> data1 [ 55: 0]
address claimToAddr --> data1 [215: 56]
uint8 claimFlags --> data1 [223:216]
uint72 claimedHearts --> data2 [ 71: 0]
address referrerAddr --> data2 [231: 72]
address indexed senderAddr
*/
event ClaimAssist(
uint256 data0,
uint256 data1,
uint256 data2,
address indexed senderAddr
);
/* StakeStart (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint16 stakedDays --> data0 [199:184]
bool isAutoStake --> data0 [207:200]
*/
event StakeStart(
uint256 data0,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* StakeGoodAccounting(auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
address indexed senderAddr
*/
event StakeGoodAccounting(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId,
address indexed senderAddr
);
/* StakeEnd (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
address indexed stakerAddr
uint40 indexed stakeId
uint72 stakedHearts --> data0 [111: 40]
uint72 stakeShares --> data0 [183:112]
uint72 payout --> data0 [255:184]
uint72 penalty --> data1 [ 71: 0]
uint16 servedDays --> data1 [ 87: 72]
bool prevUnlocked --> data1 [ 95: 88]
*/
event StakeEnd(
uint256 data0,
uint256 data1,
address indexed stakerAddr,
uint40 indexed stakeId
);
/* ShareRateChange (auto-generated event)
uint40 timestamp --> data0 [ 39: 0]
uint40 shareRate --> data0 [ 79: 40]
uint40 indexed stakeId
*/
event ShareRateChange(
uint256 data0,
uint40 indexed stakeId
);
/* Origin address */
address internal constant ORIGIN_ADDR = 0x9A6a414D6F3497c05E3b1De90520765fA1E07c03;
/* Flush address */
address payable internal constant FLUSH_ADDR = 0x1028132da0B246F5FdDE135fB8B27166766f9c30;
/* ERC20 constants */
string public constant name = "HEX TOKEN";
string public constant symbol = "HEXTKN";
uint8 public constant decimals = 8;
/* Hearts per Satoshi = 10,000 * 1e8 / 1e8 = 1e4 */
uint256 private constant HEARTS_PER_HEX = 10 ** uint256(decimals); // 1e8
uint256 private constant HEX_PER_BTC = 1e4;
uint256 private constant SATOSHIS_PER_BTC = 1e8;
uint256 internal constant HEARTS_PER_SATOSHI = HEARTS_PER_HEX / SATOSHIS_PER_BTC * HEX_PER_BTC;
/* Time of contract launch (2019-12-03T00:00:00Z) */
uint256 internal constant LAUNCH_TIME = 1575331200;
/* Size of a Hearts or Shares uint */
uint256 internal constant HEART_UINT_SIZE = 72;
/* Size of a transform lobby entry index uint */
uint256 internal constant XF_LOBBY_ENTRY_INDEX_SIZE = 40;
uint256 internal constant XF_LOBBY_ENTRY_INDEX_MASK = (1 << XF_LOBBY_ENTRY_INDEX_SIZE) - 1;
/* Seed for WAAS Lobby */
uint256 internal constant WAAS_LOBBY_SEED_HEX = 1e9;
uint256 internal constant WAAS_LOBBY_SEED_HEARTS = WAAS_LOBBY_SEED_HEX * HEARTS_PER_HEX;
/* Start of claim phase */
uint256 internal constant PRE_CLAIM_DAYS = 1;
uint256 internal constant CLAIM_PHASE_START_DAY = PRE_CLAIM_DAYS;
/* Length of claim phase */
uint256 private constant CLAIM_PHASE_WEEKS = 50;
uint256 internal constant CLAIM_PHASE_DAYS = CLAIM_PHASE_WEEKS * 7;
/* End of claim phase */
uint256 internal constant CLAIM_PHASE_END_DAY = CLAIM_PHASE_START_DAY + CLAIM_PHASE_DAYS;
/* Number of words to hold 1 bit for each transform lobby day */
uint256 internal constant XF_LOBBY_DAY_WORDS = (CLAIM_PHASE_END_DAY + 255) >> 8;
/* BigPayDay */
uint256 internal constant BIG_PAY_DAY = CLAIM_PHASE_END_DAY + 1;
/* Root hash of the UTXO Merkle tree */
bytes32 internal constant MERKLE_TREE_ROOT = 0x4e831acb4223b66de3b3d2e54a2edeefb0de3d7916e2886a4b134d9764d41bec;
/* Size of a Satoshi claim uint in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_SATOSHI_SIZE = 45;
/* Zero-fill between BTC address and Satoshis in a Merkle leaf */
uint256 internal constant MERKLE_LEAF_FILL_SIZE = 256 - 160 - MERKLE_LEAF_SATOSHI_SIZE;
uint256 internal constant MERKLE_LEAF_FILL_BASE = (1 << MERKLE_LEAF_FILL_SIZE) - 1;
uint256 internal constant MERKLE_LEAF_FILL_MASK = MERKLE_LEAF_FILL_BASE << MERKLE_LEAF_SATOSHI_SIZE;
/* Size of a Satoshi total uint */
uint256 internal constant SATOSHI_UINT_SIZE = 51;
uint256 internal constant SATOSHI_UINT_MASK = (1 << SATOSHI_UINT_SIZE) - 1;
/* Total Satoshis from all BTC addresses in UTXO snapshot */
uint256 internal constant FULL_SATOSHIS_TOTAL = 1807766732160668;
/* Total Satoshis from supported BTC addresses in UTXO snapshot after applying Silly Whale */
uint256 internal constant CLAIMABLE_SATOSHIS_TOTAL = 910087996911001;
/* Number of claimable BTC addresses in UTXO snapshot */
uint256 internal constant CLAIMABLE_BTC_ADDR_COUNT = 27997742;
/* Largest BTC address Satoshis balance in UTXO snapshot (sanity check) */
uint256 internal constant MAX_BTC_ADDR_BALANCE_SATOSHIS = 25550214098481;
/* Percentage of total claimed Hearts that will be auto-staked from a claim */
uint256 internal constant AUTO_STAKE_CLAIM_PERCENT = 90;
/* Stake timing parameters */
uint256 internal constant MIN_STAKE_DAYS = 1;
uint256 internal constant MIN_AUTO_STAKE_DAYS = 350;
uint256 internal constant MAX_STAKE_DAYS = 5555; // Approx 15 years
uint256 internal constant EARLY_PENALTY_MIN_DAYS = 90;
uint256 private constant LATE_PENALTY_GRACE_WEEKS = 2;
uint256 internal constant LATE_PENALTY_GRACE_DAYS = LATE_PENALTY_GRACE_WEEKS * 7;
uint256 private constant LATE_PENALTY_SCALE_WEEKS = 100;
uint256 internal constant LATE_PENALTY_SCALE_DAYS = LATE_PENALTY_SCALE_WEEKS * 7;
/* Stake shares Longer Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant LPB_BONUS_PERCENT = 20;
uint256 private constant LPB_BONUS_MAX_PERCENT = 200;
uint256 internal constant LPB = 364 * 100 / LPB_BONUS_PERCENT;
uint256 internal constant LPB_MAX_DAYS = LPB * LPB_BONUS_MAX_PERCENT / 100;
/* Stake shares Bigger Pays Better bonus constants used by _stakeStartBonusHearts() */
uint256 private constant BPB_BONUS_PERCENT = 10;
uint256 private constant BPB_MAX_HEX = 150 * 1e6;
uint256 internal constant BPB_MAX_HEARTS = BPB_MAX_HEX * HEARTS_PER_HEX;
uint256 internal constant BPB = BPB_MAX_HEARTS * 100 / BPB_BONUS_PERCENT;
/* Share rate is scaled to increase precision */
uint256 internal constant SHARE_RATE_SCALE = 1e5;
/* Share rate max (after scaling) */
uint256 internal constant SHARE_RATE_UINT_SIZE = 40;
uint256 internal constant SHARE_RATE_MAX = (1 << SHARE_RATE_UINT_SIZE) - 1;
/* Constants for preparing the claim message text */
uint8 internal constant ETH_ADDRESS_BYTE_LEN = 20;
uint8 internal constant ETH_ADDRESS_HEX_LEN = ETH_ADDRESS_BYTE_LEN * 2;
uint8 internal constant CLAIM_PARAM_HASH_BYTE_LEN = 12;
uint8 internal constant CLAIM_PARAM_HASH_HEX_LEN = CLAIM_PARAM_HASH_BYTE_LEN * 2;
uint8 internal constant BITCOIN_SIG_PREFIX_LEN = 24;
bytes24 internal constant BITCOIN_SIG_PREFIX_STR = "Bitcoin Signed Message:\n";
bytes internal constant STD_CLAIM_PREFIX_STR = "Claim_HEX_to_0x";
bytes internal constant OLD_CLAIM_PREFIX_STR = "Claim_BitcoinHEX_to_0x";
bytes16 internal constant HEX_DIGITS = "0123456789abcdef";
/* Claim flags passed to btcAddressClaim() */
uint8 internal constant CLAIM_FLAG_MSG_PREFIX_OLD = 1 << 0;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_COMPRESSED = 1 << 1;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_P2WPKH_IN_P2SH = 1 << 2;
uint8 internal constant CLAIM_FLAG_BTC_ADDR_BECH32 = 1 << 3;
uint8 internal constant CLAIM_FLAG_ETH_ADDR_LOWERCASE = 1 << 4;
/* Globals expanded for memory (except _latestStakeId) and compact for storage */
struct GlobalsCache {
// 1
uint256 _lockedHeartsTotal;
uint256 _nextStakeSharesTotal;
uint256 _shareRate;
uint256 _stakePenaltyTotal;
// 2
uint256 _dailyDataCount;
uint256 _stakeSharesTotal;
uint40 _latestStakeId;
uint256 _unclaimedSatoshisTotal;
uint256 _claimedSatoshisTotal;
uint256 _claimedBtcAddrCount;
//
uint256 _currentDay;
}
struct GlobalsStore {
// 1
uint72 lockedHeartsTotal;
uint72 nextStakeSharesTotal;
uint40 shareRate;
uint72 stakePenaltyTotal;
// 2
uint16 dailyDataCount;
uint72 stakeSharesTotal;
uint40 latestStakeId;
uint128 claimStats;
}
GlobalsStore public globals;
/* Claimed BTC addresses */
mapping(bytes20 => bool) public btcAddressClaims;
/* Daily data */
struct DailyDataStore {
uint72 dayPayoutTotal;
uint72 dayStakeSharesTotal;
uint56 dayUnclaimedSatoshisTotal;
}
mapping(uint256 => DailyDataStore) public dailyData;
/* Stake expanded for memory (except _stakeId) and compact for storage */
struct StakeCache {
uint40 _stakeId;
uint256 _stakedHearts;
uint256 _stakeShares;
uint256 _lockedDay;
uint256 _stakedDays;
uint256 _unlockedDay;
bool _isAutoStake;
}
struct StakeStore {
uint40 stakeId;
uint72 stakedHearts;
uint72 stakeShares;
uint16 lockedDay;
uint16 stakedDays;
uint16 unlockedDay;
bool isAutoStake;
}
mapping(address => StakeStore[]) public stakeLists;
/* Temporary state for calculating daily rounds */
struct DailyRoundState {
uint256 _allocSupplyCached;
uint256 _mintOriginBatch;
uint256 _payoutTotal;
}
struct XfLobbyEntryStore {
uint96 rawAmount;
address referrerAddr;
}
struct XfLobbyQueueStore {
uint40 headIndex;
uint40 tailIndex;
mapping(uint256 => XfLobbyEntryStore) entries;
}
mapping(uint256 => uint256) public xfLobby;
mapping(uint256 => mapping(address => XfLobbyQueueStore)) public xfLobbyMembers;
/**
* @dev PUBLIC FACING: Optionally update daily data for a smaller
* range to reduce gas cost for a subsequent operation
* @param beforeDay Only update days before this day number (optional; 0 for current day)
*/
function dailyDataUpdate(uint256 beforeDay)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Skip pre-claim period */
require(g._currentDay > CLAIM_PHASE_START_DAY, "HEX: Too early");
if (beforeDay != 0) {
require(beforeDay <= g._currentDay, "HEX: beforeDay cannot be in the future");
_dailyDataUpdate(g, beforeDay, false);
} else {
/* Default to updating before current day */
_dailyDataUpdate(g, g._currentDay, false);
}
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of daily data with
* a single call. Ugly implementation due to limitations of the standard ABI encoder.
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of packed values
*/
function dailyDataRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(beginDay < endDay && endDay <= globals.dailyDataCount, "HEX: range invalid");
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
uint256 v;
do {
v = uint256(dailyData[src].dayUnclaimedSatoshisTotal) << (HEART_UINT_SIZE * 2);
v |= uint256(dailyData[src].dayStakeSharesTotal) << HEART_UINT_SIZE;
v |= uint256(dailyData[src].dayPayoutTotal);
list[dst++] = v;
} while (++src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: External helper to return most global info with a single call.
* Ugly implementation due to limitations of the standard ABI encoder.
* @return Fixed array of values
*/
function globalInfo()
external
view
returns (uint256[13] memory)
{
uint256 _claimedBtcAddrCount;
uint256 _claimedSatoshisTotal;
uint256 _unclaimedSatoshisTotal;
(_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
return [
// 1
globals.lockedHeartsTotal,
globals.nextStakeSharesTotal,
globals.shareRate,
globals.stakePenaltyTotal,
// 2
globals.dailyDataCount,
globals.stakeSharesTotal,
globals.latestStakeId,
_unclaimedSatoshisTotal,
_claimedSatoshisTotal,
_claimedBtcAddrCount,
//
block.timestamp,
totalSupply(),
xfLobby[_currentDay()]
];
}
/**
* @dev PUBLIC FACING: ERC20 totalSupply() is the circulating supply and does not include any
* staked Hearts. allocatedSupply() includes both.
* @return Allocated Supply in Hearts
*/
function allocatedSupply()
external
view
returns (uint256)
{
return totalSupply() + globals.lockedHeartsTotal;
}
/**
* @dev PUBLIC FACING: External helper for the current day number since launch time
* @return Current day number (zero-based)
*/
function currentDay()
external
view
returns (uint256)
{
return _currentDay();
}
function _currentDay()
internal
view
returns (uint256)
{
return (block.timestamp - LAUNCH_TIME) / 1 days;
}
function _dailyDataUpdateAuto(GlobalsCache memory g)
internal
{
_dailyDataUpdate(g, g._currentDay, true);
}
function _globalsLoad(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
view
{
// 1
g._lockedHeartsTotal = globals.lockedHeartsTotal;
g._nextStakeSharesTotal = globals.nextStakeSharesTotal;
g._shareRate = globals.shareRate;
g._stakePenaltyTotal = globals.stakePenaltyTotal;
// 2
g._dailyDataCount = globals.dailyDataCount;
g._stakeSharesTotal = globals.stakeSharesTotal;
g._latestStakeId = globals.latestStakeId;
(g._claimedBtcAddrCount, g._claimedSatoshisTotal, g._unclaimedSatoshisTotal) = _claimStatsDecode(
globals.claimStats
);
//
g._currentDay = _currentDay();
_globalsCacheSnapshot(g, gSnapshot);
}
function _globalsCacheSnapshot(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
pure
{
// 1
gSnapshot._lockedHeartsTotal = g._lockedHeartsTotal;
gSnapshot._nextStakeSharesTotal = g._nextStakeSharesTotal;
gSnapshot._shareRate = g._shareRate;
gSnapshot._stakePenaltyTotal = g._stakePenaltyTotal;
// 2
gSnapshot._dailyDataCount = g._dailyDataCount;
gSnapshot._stakeSharesTotal = g._stakeSharesTotal;
gSnapshot._latestStakeId = g._latestStakeId;
gSnapshot._unclaimedSatoshisTotal = g._unclaimedSatoshisTotal;
gSnapshot._claimedSatoshisTotal = g._claimedSatoshisTotal;
gSnapshot._claimedBtcAddrCount = g._claimedBtcAddrCount;
}
function _globalsSync(GlobalsCache memory g, GlobalsCache memory gSnapshot)
internal
{
if (g._lockedHeartsTotal != gSnapshot._lockedHeartsTotal
|| g._nextStakeSharesTotal != gSnapshot._nextStakeSharesTotal
|| g._shareRate != gSnapshot._shareRate
|| g._stakePenaltyTotal != gSnapshot._stakePenaltyTotal) {
// 1
globals.lockedHeartsTotal = uint72(g._lockedHeartsTotal);
globals.nextStakeSharesTotal = uint72(g._nextStakeSharesTotal);
globals.shareRate = uint40(g._shareRate);
globals.stakePenaltyTotal = uint72(g._stakePenaltyTotal);
}
if (g._dailyDataCount != gSnapshot._dailyDataCount
|| g._stakeSharesTotal != gSnapshot._stakeSharesTotal
|| g._latestStakeId != gSnapshot._latestStakeId
|| g._unclaimedSatoshisTotal != gSnapshot._unclaimedSatoshisTotal
|| g._claimedSatoshisTotal != gSnapshot._claimedSatoshisTotal
|| g._claimedBtcAddrCount != gSnapshot._claimedBtcAddrCount) {
// 2
globals.dailyDataCount = uint16(g._dailyDataCount);
globals.stakeSharesTotal = uint72(g._stakeSharesTotal);
globals.latestStakeId = g._latestStakeId;
globals.claimStats = _claimStatsEncode(
g._claimedBtcAddrCount,
g._claimedSatoshisTotal,
g._unclaimedSatoshisTotal
);
}
}
function _stakeLoad(StakeStore storage stRef, uint40 stakeIdParam, StakeCache memory st)
internal
view
{
/* Ensure caller's stakeIndex is still current */
require(stakeIdParam == stRef.stakeId, "HEX: stakeIdParam not in stake");
st._stakeId = stRef.stakeId;
st._stakedHearts = stRef.stakedHearts;
st._stakeShares = stRef.stakeShares;
st._lockedDay = stRef.lockedDay;
st._stakedDays = stRef.stakedDays;
st._unlockedDay = stRef.unlockedDay;
st._isAutoStake = stRef.isAutoStake;
}
function _stakeUpdate(StakeStore storage stRef, StakeCache memory st)
internal
{
stRef.stakeId = st._stakeId;
stRef.stakedHearts = uint72(st._stakedHearts);
stRef.stakeShares = uint72(st._stakeShares);
stRef.lockedDay = uint16(st._lockedDay);
stRef.stakedDays = uint16(st._stakedDays);
stRef.unlockedDay = uint16(st._unlockedDay);
stRef.isAutoStake = st._isAutoStake;
}
function _stakeAdd(
StakeStore[] storage stakeListRef,
uint40 newStakeId,
uint256 newStakedHearts,
uint256 newStakeShares,
uint256 newLockedDay,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
stakeListRef.push(
StakeStore(
newStakeId,
uint72(newStakedHearts),
uint72(newStakeShares),
uint16(newLockedDay),
uint16(newStakedDays),
uint16(0), // unlockedDay
newAutoStake
)
);
}
/**
* @dev Efficiently delete from an unordered array by moving the last element
* to the "hole" and reducing the array length. Can change the order of the list
* and invalidate previously held indexes.
* @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd()
* @param stakeListRef Reference to stakeLists[stakerAddr] array in storage
* @param stakeIndex Index of the element to delete
*/
function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex)
internal
{
uint256 lastIndex ; //inject UNINIT LOCAL/STATE VAR
/* Skip the copy if element to be removed is already the last element */
if (stakeIndex != lastIndex) {
/* Copy last element to the requested element's "hole" */
stakeListRef[stakeIndex] = stakeListRef[lastIndex];
}
/*
Reduce the array length now that the array is contiguous.
Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex'
*/
stakeListRef.pop();
}
function _claimStatsEncode(
uint256 _claimedBtcAddrCount,
uint256 _claimedSatoshisTotal,
uint256 _unclaimedSatoshisTotal
)
internal
pure
returns (uint128)
{
uint256 v ; //inject UNINIT LOCAL/STATE VAR
v |= _claimedSatoshisTotal << SATOSHI_UINT_SIZE;
v |= _unclaimedSatoshisTotal;
return uint128(v);
}
function _claimStatsDecode(uint128 v)
internal
pure
returns (uint256 _claimedBtcAddrCount, uint256 _claimedSatoshisTotal, uint256 _unclaimedSatoshisTotal)
{
_claimedBtcAddrCount = v >> (SATOSHI_UINT_SIZE * 2);
_claimedSatoshisTotal = (v >> SATOSHI_UINT_SIZE) & SATOSHI_UINT_MASK;
_unclaimedSatoshisTotal = v & SATOSHI_UINT_MASK;
return (_claimedBtcAddrCount, _claimedSatoshisTotal, _unclaimedSatoshisTotal);
}
/**
* @dev Estimate the stake payout for an incomplete day
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param day Day to calculate bonuses for
* @return Payout in Hearts
*/
function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day)
internal
view
returns (uint256 payout)
{
/* Prevent updating state for this estimation */
GlobalsCache memory gTmp;
_globalsCacheSnapshot(g, gTmp);
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
_dailyRoundCalc(gTmp, rs, day);
/* Stake is no longer locked so it must be added to total as if it were */
gTmp._stakeSharesTotal += stakeSharesParam;
payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal;
if (day == BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(gTmp, bigPaySlice);
}
return payout;
}
function _calcAdoptionBonus(GlobalsCache memory g, uint256 payout)
internal
pure
returns (uint256)
{
/*
VIRAL REWARDS: Add adoption percentage bonus to payout
viral = payout * (claimedBtcAddrCount / CLAIMABLE_BTC_ADDR_COUNT)
*/
uint256 viral ; //inject UNINIT LOCAL/STATE VAR
/*
CRIT MASS REWARDS: Add adoption percentage bonus to payout
crit = payout * (claimedSatoshisTotal / CLAIMABLE_SATOSHIS_TOTAL)
*/
uint256 crit ; //inject UNINIT LOCAL/STATE VAR
return viral + crit;
}
function _dailyRoundCalc(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
pure
{
/*
Calculate payout round
Inflation of 3.69% inflation per 364 days (approx 1 year)
dailyInterestRate = exp(log(1 + 3.69%) / 364) - 1
= exp(log(1 + 0.0369) / 364) - 1
= exp(log(1.0369) / 364) - 1
= 0.000099553011616349 (approx)
payout = allocSupply * dailyInterestRate
= allocSupply / (1 / dailyInterestRate)
= allocSupply / (1 / 0.000099553011616349)
= allocSupply / 10044.899534066692 (approx)
= allocSupply * 10000 / 100448995 (* 10000/10000 for int precision)
*/
rs._payoutTotal = rs._allocSupplyCached * 10000 / 100448995;
if (day < CLAIM_PHASE_END_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonus ; //inject UNINIT LOCAL/STATE VAR
rs._mintOriginBatch += originBonus;
rs._allocSupplyCached += originBonus;
rs._payoutTotal += _calcAdoptionBonus(g, rs._payoutTotal);
}
if (g._stakePenaltyTotal != 0) {
rs._payoutTotal += g._stakePenaltyTotal;
g._stakePenaltyTotal = 0;
}
}
function _dailyRoundCalcAndStore(GlobalsCache memory g, DailyRoundState memory rs, uint256 day)
private
{
_dailyRoundCalc(g, rs, day);
dailyData[day].dayPayoutTotal = uint72(rs._payoutTotal);
dailyData[day].dayStakeSharesTotal = uint72(g._stakeSharesTotal);
dailyData[day].dayUnclaimedSatoshisTotal = uint56(g._unclaimedSatoshisTotal);
}
function _dailyDataUpdate(GlobalsCache memory g, uint256 beforeDay, bool isAutoUpdate)
private
{
if (g._dailyDataCount >= beforeDay) {
/* Already up-to-date */
return;
}
DailyRoundState memory rs;
rs._allocSupplyCached = totalSupply() + g._lockedHeartsTotal;
uint256 day ; //inject UNINIT LOCAL/STATE VAR
_dailyRoundCalcAndStore(g, rs, day);
/* Stakes started during this day are added to the total the next day */
if (g._nextStakeSharesTotal != 0) {
g._stakeSharesTotal += g._nextStakeSharesTotal;
g._nextStakeSharesTotal = 0;
}
while (++day < beforeDay) {
_dailyRoundCalcAndStore(g, rs, day);
}
_emitDailyDataUpdate(g._dailyDataCount, day, isAutoUpdate);
g._dailyDataCount = day;
if (rs._mintOriginBatch != 0) {
_mint(ORIGIN_ADDR, rs._mintOriginBatch);
}
}
function _emitDailyDataUpdate(uint256 beginDay, uint256 endDay, bool isAutoUpdate)
private
{
emit DailyDataUpdate( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint16(beginDay)) << 40)
| (uint256(uint16(endDay)) << 56)
| (isAutoUpdate ? (1 << 72) : 0),
msg.sender
);
}
}
contract StakeableToken is GlobalsAndUtility {
/**
* @dev PUBLIC FACING: Open a stake.
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function stakeStart(uint256 newStakedHearts, uint256 newStakedDays)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* Enforce the minimum stake time */
require(newStakedDays >= MIN_STAKE_DAYS, "HEX: newStakedDays lower than minimum");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
_stakeStart(g, newStakedHearts, newStakedDays, false);
/* Remove staked Hearts from balance of staker */
_burn(msg.sender, newStakedHearts);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty
* immediately. The staker must still call stakeEnd() to retrieve their stake return (if any).
* @param stakerAddr Address of staker
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
/* require() is more informative than the default assert() */
require(stakeLists[stakerAddr].length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeLists[stakerAddr].length, "HEX: stakeIndex invalid");
StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex];
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stRef, stakeIdParam, st);
/* Stake must have served full term */
require(g._currentDay >= st._lockedDay + st._stakedDays, "HEX: Stake not fully served");
/* Stake must still be locked */
require(st._unlockedDay == 0, "HEX: Stake already unlocked");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Unlock the completed stake */
_stakeUnlock(g, st);
/* stakeReturn value is unused here */
(, uint256 payout, uint256 penalty, uint256 cappedPenalty) = _stakePerformance(
g,
st,
st._stakedDays
);
_emitStakeGoodAccounting(
stakerAddr,
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty
);
if (cappedPenalty != 0) {
_splitPenaltyProceeds(g, cappedPenalty);
}
/* st._unlockedDay has changed */
_stakeUpdate(stRef, st);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so
* a stake id is used to reject stale indexes.
* @param stakeIndex Index of stake within stake list
* @param stakeIdParam The stake's id
*/
function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam)
external
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
StakeStore[] storage stakeListRef = stakeLists[msg.sender];
/* require() is more informative than the default assert() */
require(stakeListRef.length != 0, "HEX: Empty stake list");
require(stakeIndex < stakeListRef.length, "HEX: stakeIndex invalid");
/* Get stake copy */
StakeCache memory st;
_stakeLoad(stakeListRef[stakeIndex], stakeIdParam, st);
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
uint256 servedDays ; //inject UNINIT LOCAL/STATE VAR
bool prevUnlocked ; //inject UNINIT LOCAL/STATE VAR
uint256 stakeReturn;
uint256 payout ; //inject UNINIT LOCAL/STATE VAR
uint256 penalty ; //inject UNINIT LOCAL/STATE VAR
uint256 cappedPenalty ; //inject UNINIT LOCAL/STATE VAR
if (g._currentDay >= st._lockedDay) {
if (prevUnlocked) {
/* Previously unlocked in stakeGoodAccounting(), so must have served full term */
servedDays = st._stakedDays;
} else {
_stakeUnlock(g, st);
servedDays = g._currentDay - st._lockedDay;
if (servedDays > st._stakedDays) {
servedDays = st._stakedDays;
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
if (servedDays < MIN_AUTO_STAKE_DAYS) {
require(!st._isAutoStake, "HEX: Auto-stake still locked");
}
}
}
(stakeReturn, payout, penalty, cappedPenalty) = _stakePerformance(g, st, servedDays);
} else {
/* Deny early-unstake before an auto-stake minimum has been served */
require(!st._isAutoStake, "HEX: Auto-stake still locked");
/* Stake hasn't been added to the total yet, so no penalties or rewards apply */
g._nextStakeSharesTotal -= st._stakeShares;
stakeReturn = st._stakedHearts;
}
_emitStakeEnd(
stakeIdParam,
st._stakedHearts,
st._stakeShares,
payout,
penalty,
servedDays,
prevUnlocked
);
if (cappedPenalty != 0 && !prevUnlocked) {
/* Split penalty proceeds only if not previously unlocked by stakeGoodAccounting() */
_splitPenaltyProceeds(g, cappedPenalty);
}
/* Pay the stake return, if any, to the staker */
if (stakeReturn != 0) {
_mint(msg.sender, stakeReturn);
/* Update the share rate if necessary */
_shareRateUpdate(g, st, stakeReturn);
}
g._lockedHeartsTotal -= st._stakedHearts;
_stakeRemove(stakeListRef, stakeIndex);
_globalsSync(g, gSnapshot);
}
/**
* @dev PUBLIC FACING: Return the current stake count for a staker address
* @param stakerAddr Address of staker
*/
function stakeCount(address stakerAddr)
external
view
returns (uint256)
{
return stakeLists[stakerAddr].length;
}
/**
* @dev Open a stake.
* @param g Cache of stored globals
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
* @param newAutoStake Stake is automatic directly from a new claim
*/
function _stakeStart(
GlobalsCache memory g,
uint256 newStakedHearts,
uint256 newStakedDays,
bool newAutoStake
)
internal
{
/* Enforce the maximum stake time */
require(newStakedDays <= MAX_STAKE_DAYS, "HEX: newStakedDays higher than maximum");
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newStakeShares ; //inject UNINIT LOCAL/STATE VAR
/* Ensure newStakedHearts is enough for at least one stake share */
require(newStakeShares != 0, "HEX: newStakedHearts must be at least minimum shareRate");
/*
The stakeStart timestamp will always be part-way through the current
day, so it needs to be rounded-up to the next day to ensure all
stakes align with the same fixed calendar days. The current day is
already rounded-down, so rounded-up is current day + 1.
*/
uint256 newLockedDay ; //inject UNINIT LOCAL/STATE VAR
/* Create Stake */
uint40 newStakeId ; //inject UNINIT LOCAL/STATE VAR
_stakeAdd(
stakeLists[msg.sender],
newStakeId,
newStakedHearts,
newStakeShares,
newLockedDay,
newStakedDays,
newAutoStake
);
_emitStakeStart(newStakeId, newStakedHearts, newStakeShares, newStakedDays, newAutoStake);
/* Stake is added to total in the next round, not the current round */
g._nextStakeSharesTotal += newStakeShares;
/* Track total staked Hearts for inflation calculations */
g._lockedHeartsTotal += newStakedHearts;
}
/**
* @dev Calculates total stake payout including rewards for a multi-day range
* @param g Cache of stored globals
* @param stakeSharesParam Param from stake to calculate bonuses for
* @param beginDay First day to calculate bonuses for
* @param endDay Last day (non-inclusive) of range to calculate bonuses for
* @return Payout in Hearts
*/
function _calcPayoutRewards(
GlobalsCache memory g,
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
private
view
returns (uint256 payout)
{
for (uint256 day ; day < endDay; day++) { //inject UNINIT LOCAL/STATE VAR
payout += dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
}
/* Less expensive to re-read storage than to have the condition inside the loop */
if (beginDay <= BIG_PAY_DAY && endDay > BIG_PAY_DAY) {
uint256 bigPaySlice ; //inject UNINIT LOCAL/STATE VAR
payout += bigPaySlice + _calcAdoptionBonus(g, bigPaySlice);
}
return payout;
}
/**
* @dev Calculate bonus Hearts for a new stake, if any
* @param newStakedHearts Number of Hearts to stake
* @param newStakedDays Number of days to stake
*/
function _stakeStartBonusHearts(uint256 newStakedHearts, uint256 newStakedDays)
private
pure
returns (uint256 bonusHearts)
{
/*
LONGER PAYS BETTER:
If longer than 1 day stake is committed to, each extra day
gives bonus shares of approximately 0.0548%, which is approximately 20%
extra per year of increased stake length committed to, but capped to a
maximum of 200% extra.
extraDays = stakedDays - 1
longerBonus% = (extraDays / 364) * 20%
= (extraDays / 364) / 5
= extraDays / 1820
= extraDays / LPB
extraDays = longerBonus% * 1820
extraDaysMax = longerBonusMax% * 1820
= 200% * 1820
= 3640
= LPB_MAX_DAYS
BIGGER PAYS BETTER:
Bonus percentage scaled 0% to 10% for the first 150M HEX of stake.
biggerBonus% = (cappedHearts / BPB_MAX_HEARTS) * 10%
= (cappedHearts / BPB_MAX_HEARTS) / 10
= cappedHearts / (BPB_MAX_HEARTS * 10)
= cappedHearts / BPB
COMBINED:
combinedBonus% = longerBonus% + biggerBonus%
cappedExtraDays cappedHearts
= --------------- + ------------
LPB BPB
cappedExtraDays * BPB cappedHearts * LPB
= --------------------- + ------------------
LPB * BPB LPB * BPB
cappedExtraDays * BPB + cappedHearts * LPB
= --------------------------------------------
LPB * BPB
bonusHearts = hearts * combinedBonus%
= hearts * (cappedExtraDays * BPB + cappedHearts * LPB) / (LPB * BPB)
*/
uint256 cappedExtraDays ; //inject UNINIT LOCAL/STATE VAR
/* Must be more than 1 day for Longer-Pays-Better */
if (newStakedDays > 1) {
cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS;
}
uint256 cappedStakedHearts ; //inject UNINIT LOCAL/STATE VAR
bonusHearts = cappedExtraDays * BPB + cappedStakedHearts * LPB;
bonusHearts = newStakedHearts * bonusHearts / (LPB * BPB);
return bonusHearts;
}
function _stakeUnlock(GlobalsCache memory g, StakeCache memory st)
private
pure
{
g._stakeSharesTotal -= st._stakeShares;
st._unlockedDay = g._currentDay;
}
function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays)
private
view
returns (uint256 stakeReturn, uint256 payout, uint256 penalty, uint256 cappedPenalty)
{
if (servedDays < st._stakedDays) {
(payout, penalty) = _calcPayoutAndEarlyPenalty(
g,
st._lockedDay,
st._stakedDays,
servedDays,
st._stakeShares
);
stakeReturn = st._stakedHearts + payout;
} else {
// servedDays must == stakedDays here
payout = _calcPayoutRewards(
g,
st._stakeShares,
st._lockedDay,
st._lockedDay + servedDays
);
stakeReturn = st._stakedHearts + payout;
penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn);
}
if (penalty != 0) {
if (penalty > stakeReturn) {
/* Cannot have a negative stake return */
cappedPenalty = stakeReturn;
stakeReturn = 0;
} else {
/* Remove penalty from the stake return */
cappedPenalty = penalty;
stakeReturn -= cappedPenalty;
}
}
return (stakeReturn, payout, penalty, cappedPenalty);
}
function _calcPayoutAndEarlyPenalty(
GlobalsCache memory g,
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 servedDays,
uint256 stakeSharesParam
)
private
view
returns (uint256 payout, uint256 penalty)
{
uint256 servedEndDay ; //inject UNINIT LOCAL/STATE VAR
/* 50% of stakedDays (rounded up) with a minimum applied */
uint256 penaltyDays ; //inject UNINIT LOCAL/STATE VAR
if (penaltyDays < EARLY_PENALTY_MIN_DAYS) {
penaltyDays = EARLY_PENALTY_MIN_DAYS;
}
if (servedDays == 0) {
/* Fill penalty days with the estimated average payout */
uint256 expected ; //inject UNINIT LOCAL/STATE VAR
penalty = expected * penaltyDays;
return (payout, penalty); // Actual payout was 0
}
if (penaltyDays < servedDays) {
/*
Simplified explanation of intervals where end-day is non-inclusive:
penalty: [lockedDay ... penaltyEndDay)
delta: [penaltyEndDay ... servedEndDay)
payout: [lockedDay ....................... servedEndDay)
*/
uint256 penaltyEndDay ; //inject UNINIT LOCAL/STATE VAR
penalty = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, penaltyEndDay);
uint256 delta ; //inject UNINIT LOCAL/STATE VAR
payout = penalty + delta;
return (payout, penalty);
}
/* penaltyDays >= servedDays */
payout = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, servedEndDay);
if (penaltyDays == servedDays) {
penalty = payout;
} else {
/*
(penaltyDays > servedDays) means not enough days served, so fill the
penalty days with the average payout from only the days that were served.
*/
penalty = payout * penaltyDays / servedDays;
}
return (payout, penalty);
}
function _calcLatePenalty(
uint256 lockedDayParam,
uint256 stakedDaysParam,
uint256 unlockedDayParam,
uint256 rawStakeReturn
)
private
pure
returns (uint256)
{
/* Allow grace time before penalties accrue */
uint256 maxUnlockedDay ; //inject UNINIT LOCAL/STATE VAR
if (unlockedDayParam <= maxUnlockedDay) {
return 0;
}
/* Calculate penalty as a percentage of stake return based on time */
return rawStakeReturn * (unlockedDayParam - maxUnlockedDay) / LATE_PENALTY_SCALE_DAYS;
}
function _splitPenaltyProceeds(GlobalsCache memory g, uint256 penalty)
private
{
/* Split a penalty 50:50 between Origin and stakePenaltyTotal */
uint256 splitPenalty ; //inject UNINIT LOCAL/STATE VAR
if (splitPenalty != 0) {
_mint(ORIGIN_ADDR, splitPenalty);
}
/* Use the other half of the penalty to account for an odd-numbered penalty */
splitPenalty = penalty - splitPenalty;
g._stakePenaltyTotal += splitPenalty;
}
function _shareRateUpdate(GlobalsCache memory g, StakeCache memory st, uint256 stakeReturn)
private
{
if (stakeReturn > st._stakedHearts) {
/*
Calculate the new shareRate that would yield the same number of shares if
the user re-staked this stakeReturn, factoring in any bonuses they would
receive in stakeStart().
*/
uint256 bonusHearts ; //inject UNINIT LOCAL/STATE VAR
uint256 newShareRate ; //inject UNINIT LOCAL/STATE VAR
if (newShareRate > SHARE_RATE_MAX) {
/*
Realistically this can't happen, but there are contrived theoretical
scenarios that can lead to extreme values of newShareRate, so it is
capped to prevent them anyway.
*/
newShareRate = SHARE_RATE_MAX;
}
if (newShareRate > g._shareRate) {
g._shareRate = newShareRate;
_emitShareRateChange(newShareRate, st._stakeId);
}
}
}
function _emitStakeStart(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 stakedDays,
bool isAutoStake
)
private
{
emit StakeStart( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint16(stakedDays)) << 184)
| (isAutoStake ? (1 << 200) : 0),
msg.sender,
stakeId
);
}
function _emitStakeGoodAccounting(
address stakerAddr,
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty
)
private
{
emit StakeGoodAccounting( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty)),
stakerAddr,
stakeId,
msg.sender
);
}
function _emitStakeEnd(
uint40 stakeId,
uint256 stakedHearts,
uint256 stakeShares,
uint256 payout,
uint256 penalty,
uint256 servedDays,
bool prevUnlocked
)
private
{
emit StakeEnd( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(stakedHearts)) << 40)
| (uint256(uint72(stakeShares)) << 112)
| (uint256(uint72(payout)) << 184),
uint256(uint72(penalty))
| (uint256(uint16(servedDays)) << 72)
| (prevUnlocked ? (1 << 88) : 0),
msg.sender,
stakeId
);
}
function _emitShareRateChange(uint256 shareRate, uint40 stakeId)
private
{
emit ShareRateChange( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint40(shareRate)) << 40),
stakeId
);
}
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
bytes32 proofElement ; //inject UNINIT LOCAL/STATE VAR
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;
}
}
contract UTXOClaimValidation is StakeableToken {
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are unclaimed and part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if can be claimed
*/
function btcAddressIsClaimable(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
view
returns (bool)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
require(day >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(day < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Don't need to check Merkle proof if UTXO BTC address has already been claimed */
if (btcAddressClaims[btcAddr]) {
return false;
}
/* Verify the Merkle tree proof */
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _btcAddressIsValid(btcAddr, rawSatoshis, proof);
}
/**
* @dev PUBLIC FACING: Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function merkleProofIsValid(bytes32 merkleLeaf, bytes32[] calldata proof)
external
pure
returns (bool)
{
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev PUBLIC FACING: Verify that a Bitcoin signature matches the claim message containing
* the Ethereum address and claim param hash
* @param claimToAddr Eth address within the signed claim message
* @param claimParamHash Param hash within the signed claim message
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @return True if matching
*/
function claimMessageMatchesSignature(
address claimToAddr,
bytes32 claimParamHash,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s
)
public
pure
returns (bool)
{
require(v >= 27 && v <= 30, "HEX: v invalid");
/*
ecrecover() returns an Eth address rather than a public key, so
we must do the same to compare.
*/
address pubKeyEthAddr ; //inject UNINIT LOCAL/STATE VAR
/* Create and hash the claim message text */
bytes32 messageHash ; //inject UNINIT LOCAL/STATE VAR
/* Verify the public key */
return ecrecover(messageHash, v, r, s) == pubKeyEthAddr;
}
/**
* @dev PUBLIC FACING: Derive an Ethereum address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @return Derived Eth address
*/
function pubKeyToEthAddress(bytes32 pubKeyX, bytes32 pubKeyY)
public
pure
returns (address)
{
return address(uint160(uint256(keccak256(abi.encodePacked(pubKeyX, pubKeyY)))));
}
/**
* @dev PUBLIC FACING: Derive a Bitcoin address from an ECDSA public key
* @param pubKeyX First half of uncompressed ECDSA public key
* @param pubKeyY Second half of uncompressed ECDSA public key
* @param claimFlags Claim flags specifying address and message formats
* @return Derived Bitcoin address (binary; no base58-check encoding)
*/
function pubKeyToBtcAddress(bytes32 pubKeyX, bytes32 pubKeyY, uint8 claimFlags)
public
pure
returns (bytes20)
{
/*
Helpful references:
- https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses
- https://github.com/cryptocoinjs/ecurve/blob/master/lib/point.js
*/
uint8 startingByte;
bytes memory pubKey;
bool compressed ; //inject UNINIT LOCAL/STATE VAR
bool nested ; //inject UNINIT LOCAL/STATE VAR
bool bech32 ; //inject UNINIT LOCAL/STATE VAR
if (compressed) {
/* Compressed public key format */
require(!(nested && bech32), "HEX: claimFlags invalid");
startingByte = (pubKeyY[31] & 0x01) == 0 ? 0x02 : 0x03;
pubKey = abi.encodePacked(startingByte, pubKeyX);
} else {
/* Uncompressed public key format */
require(!nested && !bech32, "HEX: claimFlags invalid");
startingByte = 0x04;
pubKey = abi.encodePacked(startingByte, pubKeyX, pubKeyY);
}
bytes20 pubKeyHash ; //inject UNINIT LOCAL/STATE VAR
if (nested) {
return _hash160(abi.encodePacked(hex"0014", pubKeyHash));
}
return pubKeyHash;
}
/**
* @dev Verify a BTC address and balance are part of the Merkle tree
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @return True if valid
*/
function _btcAddressIsValid(bytes20 btcAddr, uint256 rawSatoshis, bytes32[] memory proof)
internal
pure
returns (bool)
{
/*
Ensure the proof does not attempt to treat a Merkle leaf as if it were an
internal Merkle tree node. A leaf will always have the zero-fill. An
internal node will never have the zero-fill, as guaranteed by HEX's Merkle
tree construction.
The first element, proof[0], will always be a leaf because it is the pair
of the leaf being validated. The rest of the elements, proof[1..length-1],
must be internal nodes.
The number of leaves (CLAIMABLE_BTC_ADDR_COUNT) is even, as guaranteed by
HEX's Merkle tree construction, which eliminates the only edge-case where
this validation would not apply.
*/
require((uint256(proof[0]) & MERKLE_LEAF_FILL_MASK) == 0, "HEX: proof invalid");
for (uint256 i ; i < proof.length; i++) { //inject UNINIT LOCAL/STATE VAR
require((uint256(proof[i]) & MERKLE_LEAF_FILL_MASK) != 0, "HEX: proof invalid");
}
/*
Calculate the 32 byte Merkle leaf associated with this BTC address and balance
160 bits: BTC address
52 bits: Zero-fill
45 bits: Satoshis (limited by MAX_BTC_ADDR_BALANCE_SATOSHIS)
*/
bytes32 merkleLeaf ; //inject UNINIT LOCAL/STATE VAR
/* Verify the Merkle tree proof */
return _merkleProofIsValid(merkleLeaf, proof);
}
/**
* @dev Verify a Merkle proof using the UTXO Merkle tree
* @param merkleLeaf Leaf asserted to be present in the Merkle tree
* @param proof Generated Merkle tree proof
* @return True if valid
*/
function _merkleProofIsValid(bytes32 merkleLeaf, bytes32[] memory proof)
private
pure
returns (bool)
{
return MerkleProof.verify(proof, MERKLE_TREE_ROOT, merkleLeaf);
}
function _claimMessageCreate(address claimToAddr, bytes32 claimParamHash, uint8 claimFlags)
private
pure
returns (bytes memory)
{
bytes memory prefixStr = (claimFlags & CLAIM_FLAG_MSG_PREFIX_OLD) != 0
? OLD_CLAIM_PREFIX_STR
: STD_CLAIM_PREFIX_STR;
bool includeAddrChecksum ; //inject UNINIT LOCAL/STATE VAR
bytes memory addrStr = _addressStringCreate(claimToAddr, includeAddrChecksum);
if (claimParamHash == 0) {
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN,
prefixStr,
addrStr
);
}
bytes memory claimParamHashStr = new bytes(CLAIM_PARAM_HASH_HEX_LEN);
_hexStringFromData(claimParamHashStr, claimParamHash, CLAIM_PARAM_HASH_BYTE_LEN);
return abi.encodePacked(
BITCOIN_SIG_PREFIX_LEN,
BITCOIN_SIG_PREFIX_STR,
uint8(prefixStr.length) + ETH_ADDRESS_HEX_LEN + 1 + CLAIM_PARAM_HASH_HEX_LEN,
prefixStr,
addrStr,
"_",
claimParamHashStr
);
}
function _addressStringCreate(address addr, bool includeAddrChecksum)
private
pure
returns (bytes memory addrStr)
{
addrStr = new bytes(ETH_ADDRESS_HEX_LEN);
_hexStringFromData(addrStr, bytes32(bytes20(addr)), ETH_ADDRESS_BYTE_LEN);
if (includeAddrChecksum) {
bytes32 addrStrHash ; //inject UNINIT LOCAL/STATE VAR
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < ETH_ADDRESS_BYTE_LEN; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
_addressStringChecksumChar(addrStr, offset++, b >> 4);
_addressStringChecksumChar(addrStr, offset++, b & 0x0f);
}
}
return addrStr;
}
function _addressStringChecksumChar(bytes memory addrStr, uint256 offset, uint8 hashNybble)
private
pure
{
bytes1 ch ; //inject UNINIT LOCAL/STATE VAR
if (ch >= "a" && hashNybble >= 8) {
addrStr[offset] = ch ^ 0x20;
}
}
function _hexStringFromData(bytes memory hexStr, bytes32 data, uint256 dataLen)
private
pure
{
uint256 offset ; //inject UNINIT LOCAL/STATE VAR
for (uint256 i ; i < dataLen; i++) { //inject UNINIT LOCAL/STATE VAR
uint8 b ; //inject UNINIT LOCAL/STATE VAR
hexStr[offset++] = HEX_DIGITS[b >> 4];
hexStr[offset++] = HEX_DIGITS[b & 0x0f];
}
}
/**
* @dev sha256(sha256(data))
* @param data Data to be hashed
* @return 32-byte hash
*/
function _hash256(bytes memory data)
private
pure
returns (bytes32)
{
return sha256(abi.encodePacked(sha256(data)));
}
/**
* @dev ripemd160(sha256(data))
* @param data Data to be hashed
* @return 20-byte hash
*/
function _hash160(bytes memory data)
private
pure
returns (bytes20)
{
return ripemd160(abi.encodePacked(sha256(data)));
}
}
contract UTXORedeemableToken is UTXOClaimValidation {
/**
* @dev PUBLIC FACING: Claim a BTC address and its Satoshi balance in Hearts
* crediting the appropriate amount to a specified Eth address. Bitcoin ECDSA
* signature must be from that BTC address and must match the claim message
* for the Eth address.
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param proof Merkle tree proof
* @param claimToAddr Destination Eth address to credit Hearts to
* @param pubKeyX First half of uncompressed ECDSA public key for the BTC address
* @param pubKeyY Second half of uncompressed ECDSA public key for the BTC address
* @param claimFlags Claim flags specifying address and message formats
* @param v v parameter of ECDSA signature
* @param r r parameter of ECDSA signature
* @param s s parameter of ECDSA signature
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function btcAddressClaim(
uint256 rawSatoshis,
bytes32[] calldata proof,
address claimToAddr,
bytes32 pubKeyX,
bytes32 pubKeyY,
uint8 claimFlags,
uint8 v,
bytes32 r,
bytes32 s,
uint256 autoStakeDays,
address referrerAddr
)
external
returns (uint256)
{
/* Sanity check */
require(rawSatoshis <= MAX_BTC_ADDR_BALANCE_SATOSHIS, "HEX: CHK: rawSatoshis");
/* Enforce the minimum stake time for the auto-stake from this claim */
require(autoStakeDays >= MIN_AUTO_STAKE_DAYS, "HEX: autoStakeDays lower than minimum");
/* Ensure signature matches the claim message containing the Eth address and claimParamHash */
{
bytes32 claimParamHash ; //inject UNINIT LOCAL/STATE VAR
if (claimToAddr != msg.sender) {
/* Claimer did not send this, so claim params must be signed */
claimParamHash = keccak256(
abi.encodePacked(MERKLE_TREE_ROOT, autoStakeDays, referrerAddr)
);
}
require(
claimMessageMatchesSignature(
claimToAddr,
claimParamHash,
pubKeyX,
pubKeyY,
claimFlags,
v,
r,
s
),
"HEX: Signature mismatch"
);
}
/* Derive BTC address from public key */
bytes20 btcAddr ; //inject UNINIT LOCAL/STATE VAR
/* Ensure BTC address has not yet been claimed */
require(!btcAddressClaims[btcAddr], "HEX: BTC address balance already claimed");
/* Ensure BTC address is part of the Merkle tree */
require(
_btcAddressIsValid(btcAddr, rawSatoshis, proof),
"HEX: BTC address or balance unknown"
);
/* Mark BTC address as claimed */
btcAddressClaims[btcAddr] = true;
return _satoshisClaimSync(
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
}
function _satoshisClaimSync(
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
totalClaimedHearts = _satoshisClaim(
g,
rawSatoshis,
claimToAddr,
btcAddr,
claimFlags,
autoStakeDays,
referrerAddr
);
_globalsSync(g, gSnapshot);
return totalClaimedHearts;
}
/**
* @dev Credit an Eth address with the Hearts value of a raw Satoshis balance
* @param g Cache of stored globals
* @param rawSatoshis Raw BTC address balance in Satoshis
* @param claimToAddr Destination Eth address for the claimed Hearts to be sent
* @param btcAddr Bitcoin address (binary; no base58-check encoding)
* @param autoStakeDays Number of days to auto-stake, subject to minimum auto-stake days
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
* @return Total number of Hearts credited, if successful
*/
function _satoshisClaim(
GlobalsCache memory g,
uint256 rawSatoshis,
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 autoStakeDays,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
/* Allowed only during the claim phase */
require(g._currentDay >= CLAIM_PHASE_START_DAY, "HEX: Claim phase has not yet started");
require(g._currentDay < CLAIM_PHASE_END_DAY, "HEX: Claim phase has ended");
/* Check if log data needs to be updated */
_dailyDataUpdateAuto(g);
/* Sanity check */
require(
g._claimedBtcAddrCount < CLAIMABLE_BTC_ADDR_COUNT,
"HEX: CHK: _claimedBtcAddrCount"
);
(uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts) = _calcClaimValues(
g,
rawSatoshis
);
/* Increment claim count to track viral rewards */
g._claimedBtcAddrCount++;
totalClaimedHearts = _remitBonuses(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
claimedHearts,
claimBonusHearts,
referrerAddr
);
/* Auto-stake a percentage of the successful claim */
uint256 autoStakeHearts ; //inject UNINIT LOCAL/STATE VAR
_stakeStart(g, autoStakeHearts, autoStakeDays, true);
/* Mint remaining claimed Hearts to claim address */
_mint(claimToAddr, totalClaimedHearts - autoStakeHearts);
return totalClaimedHearts;
}
function _remitBonuses(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
uint256 claimBonusHearts,
address referrerAddr
)
private
returns (uint256 totalClaimedHearts)
{
totalClaimedHearts = claimedHearts + claimBonusHearts;
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referral bonus of 10% of total claimed Hearts to claimer */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
totalClaimedHearts += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
originBonusHearts += referralBonusHearts + referrerBonusHearts;
if (referrerAddr == claimToAddr) {
/* Self-referred */
totalClaimedHearts += referrerBonusHearts;
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
} else {
/* Referred by different address */
_emitClaim(
claimToAddr,
btcAddr,
claimFlags,
rawSatoshis,
adjSatoshis,
totalClaimedHearts,
referrerAddr
);
_mint(referrerAddr, referrerBonusHearts);
}
}
_mint(ORIGIN_ADDR, originBonusHearts);
return totalClaimedHearts;
}
function _emitClaim(
address claimToAddr,
bytes20 btcAddr,
uint8 claimFlags,
uint256 rawSatoshis,
uint256 adjSatoshis,
uint256 claimedHearts,
address referrerAddr
)
private
{
emit Claim( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint56(rawSatoshis)) << 40)
| (uint256(uint56(adjSatoshis)) << 96)
| (uint256(claimFlags) << 152)
| (uint256(uint72(claimedHearts)) << 160),
uint256(uint160(msg.sender)),
btcAddr,
claimToAddr,
referrerAddr
);
if (claimToAddr == msg.sender) {
return;
}
emit ClaimAssist( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint160(btcAddr)) << 40)
| (uint256(uint56(rawSatoshis)) << 200),
uint256(uint56(adjSatoshis))
| (uint256(uint160(claimToAddr)) << 56)
| (uint256(claimFlags) << 216),
uint256(uint72(claimedHearts))
| (uint256(uint160(referrerAddr)) << 72),
msg.sender
);
}
function _calcClaimValues(GlobalsCache memory g, uint256 rawSatoshis)
private
pure
returns (uint256 adjSatoshis, uint256 claimedHearts, uint256 claimBonusHearts)
{
/* Apply Silly Whale reduction */
adjSatoshis = _adjustSillyWhale(rawSatoshis);
require(
g._claimedSatoshisTotal + adjSatoshis <= CLAIMABLE_SATOSHIS_TOTAL,
"HEX: CHK: _claimedSatoshisTotal"
);
g._claimedSatoshisTotal += adjSatoshis;
uint256 daysRemaining ; //inject UNINIT LOCAL/STATE VAR
/* Apply late-claim reduction */
adjSatoshis = _adjustLateClaim(adjSatoshis, daysRemaining);
g._unclaimedSatoshisTotal -= adjSatoshis;
/* Convert to Hearts and calculate speed bonus */
claimedHearts = adjSatoshis * HEARTS_PER_SATOSHI;
claimBonusHearts = _calcSpeedBonus(claimedHearts, daysRemaining);
return (adjSatoshis, claimedHearts, claimBonusHearts);
}
/**
* @dev Apply Silly Whale adjustment
* @param rawSatoshis Raw BTC address balance in Satoshis
* @return Adjusted BTC address balance in Satoshis
*/
function _adjustSillyWhale(uint256 rawSatoshis)
private
pure
returns (uint256)
{
if (rawSatoshis < 1000e8) {
/* For < 1,000 BTC: no penalty */
return rawSatoshis;
}
if (rawSatoshis >= 10000e8) {
/* For >= 10,000 BTC: penalty is 75%, leaving 25% */
return rawSatoshis / 4;
}
/*
For 1,000 <= BTC < 10,000: penalty scales linearly from 50% to 75%
penaltyPercent = (btc - 1000) / (10000 - 1000) * (75 - 50) + 50
= (btc - 1000) / 9000 * 25 + 50
= (btc - 1000) / 360 + 50
appliedPercent = 100 - penaltyPercent
= 100 - ((btc - 1000) / 360 + 50)
= 100 - (btc - 1000) / 360 - 50
= 50 - (btc - 1000) / 360
= (18000 - (btc - 1000)) / 360
= (18000 - btc + 1000) / 360
= (19000 - btc) / 360
adjustedBtc = btc * appliedPercent / 100
= btc * ((19000 - btc) / 360) / 100
= btc * (19000 - btc) / 36000
adjustedSat = 1e8 * adjustedBtc
= 1e8 * (btc * (19000 - btc) / 36000)
= 1e8 * ((sat / 1e8) * (19000 - (sat / 1e8)) / 36000)
= 1e8 * (sat / 1e8) * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * 1e8 * (19000 - (sat / 1e8)) / 36000
= (sat / 1e8) * (19000e8 - sat) / 36000
= sat * (19000e8 - sat) / 36000e8
*/
return rawSatoshis * (19000e8 - rawSatoshis) / 36000e8;
}
/**
* @dev Apply late-claim adjustment to scale claim to zero by end of claim phase
* @param adjSatoshis Adjusted BTC address balance in Satoshis (after Silly Whale)
* @param daysRemaining Number of reward days remaining in claim phase
* @return Adjusted BTC address balance in Satoshis (after Silly Whale and Late-Claim)
*/
function _adjustLateClaim(uint256 adjSatoshis, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
adjustedSat = sat * (daysRemaining / CLAIM_PHASE_DAYS) * 100%
= sat * daysRemaining / CLAIM_PHASE_DAYS
*/
return adjSatoshis * daysRemaining / CLAIM_PHASE_DAYS;
}
/**
* @dev Calculates speed bonus for claiming earlier in the claim phase
* @param claimedHearts Hearts claimed from adjusted BTC address balance Satoshis
* @param daysRemaining Number of claim days remaining in claim phase
* @return Speed bonus in Hearts
*/
function _calcSpeedBonus(uint256 claimedHearts, uint256 daysRemaining)
private
pure
returns (uint256)
{
/*
Only valid from CLAIM_PHASE_DAYS to 1, and only used during that time.
Speed bonus is 20% ... 0% inclusive.
bonusHearts = claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20%
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) * 20/100
= claimedHearts * ((daysRemaining - 1) / (CLAIM_PHASE_DAYS - 1)) / 5
= claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5)
*/
return claimedHearts * (daysRemaining - 1) / ((CLAIM_PHASE_DAYS - 1) * 5);
}
}
contract TransformableToken is UTXORedeemableToken {
/**
* @dev PUBLIC FACING: Enter the tranform lobby for the current round
* @param referrerAddr Eth address of referring user (optional; 0x0 for no referrer)
*/
function xfLobbyEnter(address referrerAddr)
external
payable
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
require(enterDay < CLAIM_PHASE_END_DAY, "HEX: Lobbies have ended");
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
require(rawAmount != 0, "HEX: Amount required");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr);
xfLobby[enterDay] += rawAmount;
_emitXfLobbyEnter(enterDay, entryIndex, rawAmount, referrerAddr);
}
/**
* @dev PUBLIC FACING: Leave the transform lobby after the round is complete
* @param enterDay Day number when the member entered
* @param count Number of queued-enters to exit (optional; 0 for all)
*/
function xfLobbyExit(uint256 enterDay, uint256 count)
external
{
require(enterDay < _currentDay(), "HEX: Round is not complete");
XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender];
uint256 headIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 endIndex;
if (count != 0) {
require(count <= qRef.tailIndex - headIndex, "HEX: count invalid");
endIndex = headIndex + count;
} else {
endIndex = qRef.tailIndex;
require(headIndex < endIndex, "HEX: count invalid");
}
uint256 waasLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 _xfLobby ; //inject UNINIT LOCAL/STATE VAR
uint256 totalXfAmount ; //inject UNINIT LOCAL/STATE VAR
uint256 originBonusHearts ; //inject UNINIT LOCAL/STATE VAR
do {
uint256 rawAmount ; //inject UNINIT LOCAL/STATE VAR
address referrerAddr ; //inject UNINIT LOCAL/STATE VAR
delete qRef.entries[headIndex];
uint256 xfAmount ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == address(0)) {
/* No referrer */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referral bonus of 10% of xfAmount to member */
uint256 referralBonusHearts ; //inject UNINIT LOCAL/STATE VAR
xfAmount += referralBonusHearts;
/* Then a cumulative referrer bonus of 20% to referrer */
uint256 referrerBonusHearts ; //inject UNINIT LOCAL/STATE VAR
if (referrerAddr == msg.sender) {
/* Self-referred */
xfAmount += referrerBonusHearts;
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
} else {
/* Referred by different address */
_emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr);
_mint(referrerAddr, referrerBonusHearts);
}
originBonusHearts += referralBonusHearts + referrerBonusHearts;
}
totalXfAmount += xfAmount;
} while (++headIndex < endIndex);
qRef.headIndex = uint40(headIndex);
if (originBonusHearts != 0) {
_mint(ORIGIN_ADDR, originBonusHearts);
}
if (totalXfAmount != 0) {
_mint(msg.sender, totalXfAmount);
}
}
/**
* @dev PUBLIC FACING: Release any value that has been sent to the contract
*/
function xfLobbyFlush()
external
{
require(address(this).balance != 0, "HEX: No value");
FLUSH_ADDR.transfer(address(this).balance);
}
/**
* @dev PUBLIC FACING: External helper to return multiple values of xfLobby[] with
* a single call
* @param beginDay First day of data range
* @param endDay Last day (non-inclusive) of data range
* @return Fixed array of values
*/
function xfLobbyRange(uint256 beginDay, uint256 endDay)
external
view
returns (uint256[] memory list)
{
require(
beginDay < endDay && endDay <= CLAIM_PHASE_END_DAY && endDay <= _currentDay(),
"HEX: invalid range"
);
list = new uint256[](endDay - beginDay);
uint256 src ; //inject UNINIT LOCAL/STATE VAR
uint256 dst ; //inject UNINIT LOCAL/STATE VAR
do {
list[dst++] = uint256(xfLobby[src++]);
} while (src < endDay);
return list;
}
/**
* @dev PUBLIC FACING: Return a current lobby member queue entry.
* Only needed due to limitations of the standard ABI encoder.
* @param memberAddr Eth address of the lobby member
* @param entryId 49 bit compound value. Top 9 bits: enterDay, Bottom 40 bits: entryIndex
* @return 1: Raw amount that was entered with; 2: Referring Eth addr (optional; 0x0 for no referrer)
*/
function xfLobbyEntry(address memberAddr, uint256 entryId)
external
view
returns (uint256 rawAmount, address referrerAddr)
{
uint256 enterDay ; //inject UNINIT LOCAL/STATE VAR
uint256 entryIndex ; //inject UNINIT LOCAL/STATE VAR
XfLobbyEntryStore storage entry = xfLobbyMembers[enterDay][memberAddr].entries[entryIndex];
require(entry.rawAmount != 0, "HEX: Param invalid");
return (entry.rawAmount, entry.referrerAddr);
}
/**
* @dev PUBLIC FACING: Return the lobby days that a user is in with a single call
* @param memberAddr Eth address of the user
* @return Bit vector of lobby day numbers
*/
function xfLobbyPendingDays(address memberAddr)
external
view
returns (uint256[XF_LOBBY_DAY_WORDS] memory words)
{
uint256 day ; //inject UNINIT LOCAL/STATE VAR
if (day > CLAIM_PHASE_END_DAY) {
day = CLAIM_PHASE_END_DAY;
}
while (day-- != 0) {
if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) {
words[day >> 8] |= 1 << (day & 255);
}
}
return words;
}
function _waasLobby(uint256 enterDay)
private
returns (uint256 waasLobby)
{
if (enterDay >= CLAIM_PHASE_START_DAY) {
GlobalsCache memory g;
GlobalsCache memory gSnapshot;
_globalsLoad(g, gSnapshot);
_dailyDataUpdateAuto(g);
uint256 unclaimed ; //inject UNINIT LOCAL/STATE VAR
waasLobby = unclaimed * HEARTS_PER_SATOSHI / CLAIM_PHASE_DAYS;
_globalsSync(g, gSnapshot);
} else {
waasLobby = WAAS_LOBBY_SEED_HEARTS;
}
return waasLobby;
}
function _emitXfLobbyEnter(
uint256 enterDay,
uint256 entryIndex,
uint256 rawAmount,
address referrerAddr
)
private
{
emit XfLobbyEnter( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint96(rawAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
function _emitXfLobbyExit(
uint256 enterDay,
uint256 entryIndex,
uint256 xfAmount,
address referrerAddr
)
private
{
emit XfLobbyExit( // (auto-generated event)
uint256(uint40(block.timestamp))
| (uint256(uint72(xfAmount)) << 40),
msg.sender,
(enterDay << XF_LOBBY_ENTRY_INDEX_SIZE) | entryIndex,
referrerAddr
);
}
}
contract HEX_TOKEN is TransformableToken {
constructor()
public
{
/* Initialize global shareRate to 1 */
globals.shareRate = uint40(1 * SHARE_RATE_SCALE);
/* Initialize dailyDataCount to skip pre-claim period */
globals.dailyDataCount = uint16(PRE_CLAIM_DAYS);
/* Add all Satoshis from UTXO snapshot to contract */
globals.claimStats = _claimStatsEncode(
0, // _claimedBtcAddrCount
0, // _claimedSatoshisTotal
FULL_SATOSHIS_TOTAL // _unclaimedSatoshisTotal
);
}
function() external payable {}
} | inject UNINIT LOCAL/STATE VAR
| bool compressed ; | 1,819,093 | [
1,
22170,
5019,
12919,
15234,
19,
7998,
8350,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1426,
8968,
274,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/3/0x16A43f5829A080F1A87D2afA2716E0539fd35846/sources/Celan.sol | Direct referer commission event | event DirectReferCommission(address indexed from, address indexed to, uint value,uint time);
| 5,288,247 | [
1,
5368,
18068,
1543,
19710,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
9908,
426,
586,
799,
3951,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
460,
16,
11890,
813,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/137/0x1e3fCa63502a7AaA6841788301Eae4AC67CF691D/sources/scripts/Learning_Projects/CheeseTouch.sol | * @dev See {IERC721-transferFrom}./solhint-disable-next-line max-line-length | function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "CheeseTouch: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
| 4,755,536 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
13866,
1265,
5496,
19,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
943,
17,
1369,
17,
2469,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
1071,
5024,
3849,
288,
203,
3639,
2583,
24899,
291,
31639,
1162,
5541,
24899,
3576,
12021,
9334,
1147,
548,
3631,
315,
39,
580,
3392,
10491,
30,
7412,
4894,
353,
486,
3410,
12517,
20412,
8863,
203,
203,
3639,
389,
13866,
12,
2080,
16,
358,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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);
/**
* @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;
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 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;
}
/**
* @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 a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
contract NFY is ERC721Enumerable, ReentrancyGuard, Ownable {
IERC721 public bonusToken;
uint256 public mintPrice;
mapping(address => bool) private bonusUsed;
constructor(uint256 _totalForUsers, uint256 _totalForOwner)
ERC721("NonFungibleYou", "NFY")
Ownable()
{
totalForUsers = _totalForUsers;
totalForOwner = _totalForOwner;
bonusToken = IERC721(0xFF9C1b15B16263C61d017ee9F65C50e4AE0113D7);
}
enum AttributeType {
Age,
Handicap,
Height,
IQ,
Partner,
Penis,
Portfolio,
Race,
Sex,
Special,
Weight
}
mapping(uint256 => int256) public tokensMetadata;
uint256 public totalForUsers;
uint256 public totalForOwner;
string[] private _STRINGS = [
"RariCapital Developer",
"Zoomer",
"Millenial",
"Boomer",
"Generation X",
"Fossil",
"Peter Schiff",
"None",
"Immediately lists below mint",
"Falls for Tether FUD",
"Falls for China FUD",
"Bitcoin Maxi",
"Community Member",
"Invests in Fundamentals",
"Believes in CME gaps",
"Longs resistance, shorts support",
"Right click saves NFTs",
"Lost keys in boating accident",
"Big Boy",
"Midget",
"5'0",
"5'3",
"5'5",
"5'7",
"5'9",
"5'10",
"5'11",
"6'0",
"6'1",
"6'2",
"6'4",
"7'4",
"Size Chad",
"Brainlet",
"50 IQ",
"70 IQ",
"90 IQ",
"99 IQ",
"Ledgerstatus",
"101 IQ",
"130 IQ",
"140 IQ",
"150 IQ",
"170 IQ",
"200 IQ",
"Vitalik",
"Wizard",
"Virgin",
"Married High School Sweetheart",
"3 (more like 1)",
"1 (at least 3)",
"5",
"10",
"50",
"100",
"200",
"500",
"1000",
"Lost Count",
"1 inch",
"2 inches",
"3 inches",
"4 inches",
"5 inches",
"6 inches",
"7 inches",
"8 inches",
"10 inches",
"Mandingo",
"Negative (No-Coiner)",
"NGMI",
"2 Figure Nightmare",
"3 Figure Agony",
"4 Figure Suffering",
"5 Figure Pain",
"6 Figure Hell",
"7 Figure Purgatory",
"8 Figure Aether",
"9 Figure Heaven",
"10 Figure Bliss",
"Cobie",
"Justin Sun",
"Sam",
"Satoshi",
"Burger",
"Pajeet",
"Ni Hao, Wealthy Chinaman",
"Europoor",
"Nigerian Prince",
"Slav(e)",
"Jew",
"Unknown",
"Alien",
"Pink Wojak",
"Pepe",
"Bogdanov",
"Male",
"Female-to-male (Ticker FTM)",
"None",
"Super Slurper",
"Burger Flipper Freak",
"Rug Pull Rockstar",
"NFT Ninja",
"DeFi Deviant",
"Pixel Art Aficionado",
"Shitcoin Specialist",
"Autism",
"NEET",
"Picotop Shorter",
"Has never read A whitepaper",
"SuperCyclist",
"Friends with the Bogs",
"CEO of Based Department",
"50 lbs",
"100 lbs",
"120 lbs",
"140 lbs",
"160 lbs",
"180 lbs",
"200 lbs",
"220 lbs",
"240 lbs",
"260 lbs",
"300 lbs",
"600 lbs",
"9000 lbs",
"Messi's ROOK bags",
"Gainzy's ZEC bags"
];
uint256[3][] ages = [
[0, 0, uint256(90)],
[1, 0, uint256(2600)],
[2, 0, uint256(3300)],
[3, 0, uint256(3000)],
[4, 0, uint256(500)],
[5, 0, uint256(500)],
[6, 0, uint256(10)]
];
uint256[3][] private handicaps = [
[7, 0, uint256(1500)],
[8, 0, uint256(1500)],
[9, 0, uint256(1500)],
[10, 0, uint256(1500)],
[11, 0, uint256(1400)],
[12, 0, uint256(1000)],
[13, 0, uint256(1000)],
[14, 0, uint256(300)],
[15, 0, uint256(230)],
[16, 0, uint256(50)],
[17, 0, uint256(20)]
];
uint256[3][] private heights = [
[18, 0, uint256(5)],
[19, 0, uint256(15)],
[20, 0, uint256(100)],
[21, 0, uint256(200)],
[22, 0, uint256(700)],
[23, 0, uint256(900)],
[24, 0, uint256(1600)],
[25, 0, uint256(1600)],
[26, 0, uint256(2000)],
[27, 0, uint256(1500)],
[28, 0, uint256(900)],
[29, 0, uint256(400)],
[30, 0, uint256(50)],
[31, 0, uint256(25)],
[32, 0, uint256(5)]
];
uint256[3][] private iq = [
[33, 0, uint256(600)],
[34, 0, uint256(600)],
[35, 0, uint256(800)],
[36, 0, uint256(1400)],
[37, 0, uint256(2000)],
[38, 0, uint256(1)],
[39, 0, uint256(2000)],
[40, 0, uint256(1458)],
[41, 0, uint256(680)],
[42, 0, uint256(400)],
[43, 0, uint256(50)],
[44, 0, uint256(10)],
[45, 0, uint256(1)]
];
uint256[3][] private partners = [
[46, 0, uint256(10)],
[47, 0, uint256(5240)],
[48, 0, uint256(100)],
[49, 0, uint256(1000)],
[50, 0, uint256(1000)],
[51, 0, uint256(800)],
[52, 0, uint256(680)],
[53, 0, uint256(500)],
[54, 0, uint256(300)],
[55, 0, uint256(200)],
[56, 0, uint256(100)],
[57, 0, uint256(50)],
[58, 0, uint256(20)]
];
uint256[3][] private penises = [
[59, 0, uint256(100)],
[60, 0, uint256(200)],
[61, 0, uint256(300)],
[62, 0, uint256(1090)],
[63, 0, uint256(3000)],
[64, 0, uint256(3000)],
[65, 0, uint256(1500)],
[66, 0, uint256(500)],
[67, 0, uint256(300)],
[68, 0, uint256(10)]
];
uint256[3][] private portfolios = [
[69, 0, uint256(500)],
[70, 0, uint256(200)],
[71, 0, uint256(300)],
[72, 0, uint256(500)],
[73, 0, uint256(1214)],
[74, 0, uint256(2400)],
[75, 0, uint256(3600)],
[76, 0, uint256(800)],
[77, 0, uint256(300)],
[78, 0, uint256(100)],
[79, 0, uint256(74)],
[80, 0, uint256(5)],
[81, 0, uint256(4)],
[82, 0, uint256(2)],
[83, 0, uint256(1)]
];
uint256[3][] private races = [
[84, 0, uint256(2600)],
[85, 0, uint256(2000)],
[86, 0, uint256(2000)],
[87, 0, uint256(1400)],
[88, 0, uint256(1000)],
[89, 0, uint256(600)],
[90, 0, uint256(294)],
[91, 0, uint256(84)],
[92, 0, uint256(10)],
[93, 0, uint256(5)],
[94, 0, uint256(5)],
[95, 0, uint256(2)]
];
uint256[3][] private sexes = [[96, 0, uint256(8500)], [97, 0, uint256(1500)]];
uint256[3][] private specials = [
[98, 0, uint256(2000)],
[99, 0, uint256(1700)],
[100, 0, uint256(1000)],
[101, 0, uint256(1000)],
[102, 0, uint256(700)],
[103, 0, uint256(700)],
[104, 0, uint256(700)],
[105, 0, uint256(700)],
[106, 0, uint256(700)],
[107, 0, uint256(500)],
[108, 0, uint256(147)],
[109, 0, uint256(100)],
[110, 0, uint256(50)],
[111, 0, uint256(2)],
[112, 0, uint256(1)]
];
uint256[3][] private weights = [
[113, 0, uint256(10)],
[114, 0, uint256(20)],
[115, 0, uint256(200)],
[116, 0, uint256(500)],
[117, 0, uint256(1000)],
[118, 0, uint256(2000)],
[119, 0, uint256(2200)],
[120, 0, uint256(2000)],
[121, 0, uint256(1000)],
[122, 0, uint256(600)],
[123, 0, uint256(400)],
[124, 0, uint256(35)],
[125, 0, uint256(20)],
[126, 0, uint256(10)],
[127, 0, uint256(5)]
];
function getArrayByAttr(AttributeType attr)
internal
view
returns (uint256[3][] storage)
{
if (attr == AttributeType.Age) {
return ages;
} else if (attr == AttributeType.Handicap) {
return handicaps;
} else if (attr == AttributeType.Height) {
return heights;
} else if (attr == AttributeType.IQ) {
return iq;
} else if (attr == AttributeType.Partner) {
return partners;
} else if (attr == AttributeType.Penis) {
return penises;
} else if (attr == AttributeType.Portfolio) {
return portfolios;
} else if (attr == AttributeType.Race) {
return races;
} else if (attr == AttributeType.Sex) {
return sexes;
} else if (attr == AttributeType.Special) {
return specials;
} else if (attr == AttributeType.Weight) {
return weights;
} else {
return ages;
}
}
function setByte(
int256 n,
uint256 p,
uint256 v
) internal pure returns (int256) {
int256 i = n & int256(~(0xff << (8 * p)));
return i | int256(v << (8 * p));
}
function getByte(int256 n, uint256 p) internal pure returns (int256) {
return (n >> (8 * p)) & 0xff;
}
function getAttributeOfToken(uint256 tokenId, AttributeType attr)
internal
view
returns (uint256[3] storage)
{
int256 index = getByte(tokensMetadata[tokenId], uint256(attr));
return getArrayByAttr(attr)[uint256(index)];
}
function setAttributeOfToken(
uint256 tokenId,
AttributeType attr,
uint8 index
) internal {
tokensMetadata[tokenId] = setByte(
tokensMetadata[tokenId],
uint8(attr),
index
);
}
function getAge(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Age);
}
function getHandicap(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Handicap);
}
function getHeight(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Height);
}
function getIQ(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.IQ);
}
function getPartner(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Partner);
}
function getPenis(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Penis);
}
function getPortfolio(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Portfolio);
}
function getRace(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Race);
}
function getSex(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Sex);
}
function getSpecialTalent(uint256 tokenId)
public
view
returns (string memory)
{
return pluck(tokenId, AttributeType.Special);
}
function getWeight(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, AttributeType.Weight);
}
function pluck(uint256 tokenId, AttributeType attr)
internal
view
returns (string memory)
{
return _STRINGS[getAttributeOfToken(tokenId, attr)[0]];
}
function attributesToJson(uint256 tokenId)
internal
view
returns (string memory)
{
string[33] memory parts;
parts[0] = '{"trait_type": "Age", "value": "';
parts[1] = getAge(tokenId);
parts[2] = '"},';
parts[3] = '{"trait_type": "Sex", "value": "';
parts[4] = getSex(tokenId);
parts[5] = '"},';
parts[6] = '{"trait_type": "Race", "value": "';
parts[7] = getRace(tokenId);
parts[8] = '"},';
parts[9] = '{"trait_type": "Height", "value": "';
parts[10] = getHeight(tokenId);
parts[11] = '"},';
parts[12] = '{"trait_type": "Weight", "value": "';
parts[13] = getWeight(tokenId);
parts[14] = '"},';
parts[15] = '{"trait_type": "Penis", "value": "';
parts[16] = getPenis(tokenId);
parts[17] = '"},';
parts[18] = '{"trait_type": "Sexual Partners", "value": "';
parts[19] = getPartner(tokenId);
parts[20] = '"},';
parts[21] = '{"trait_type": "IQ", "value": "';
parts[22] = getIQ(tokenId);
parts[23] = '"},';
parts[24] = '{"trait_type": "Portfolio", "value": "';
parts[25] = getPortfolio(tokenId);
parts[26] = '"},';
parts[27] = '{"trait_type": "Special Talent", "value": "';
parts[28] = getSpecialTalent(tokenId);
parts[29] = '"},';
parts[30] = '{"trait_type": "Handicap", "value": "';
parts[31] = getHandicap(tokenId);
parts[32] = '"}';
string memory output = string(
abi.encodePacked(
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
parts[6],
parts[7],
parts[8]
)
);
output = string(
abi.encodePacked(
output,
parts[9],
parts[10],
parts[11],
parts[12],
parts[13],
parts[14],
parts[15],
parts[16]
)
);
output = string(
abi.encodePacked(
output,
parts[17],
parts[18],
parts[19],
parts[20],
parts[21],
parts[22],
parts[23],
parts[24]
)
);
output = string(
abi.encodePacked(
output,
parts[17],
parts[18],
parts[19],
parts[20],
parts[21],
parts[22],
parts[23],
parts[24]
)
);
output = string(
abi.encodePacked(
output,
parts[25],
parts[26],
parts[27],
parts[28],
parts[29],
parts[30],
parts[31],
parts[32]
)
);
return output;
}
function maxSupply() public view returns (uint256) {
return totalForUsers + totalForOwner;
}
function random(uint256 max, uint256 sq) private view returns (uint256) {
if (max == 0) {
return 0;
}
return
uint256(
keccak256(abi.encodePacked(block.difficulty, block.timestamp, sq))
) % max;
}
function removeUnfilled(int256[] storage map, uint8 index) internal {
if (map[0] == 0) {
return;
}
int256 lastIndexValue = getByte(map[1], uint256(map[0] - 1));
map[1] = setByte(map[1], index, uint256(lastIndexValue));
map[1] = setByte(map[1], uint256(map[0] - 1), 0);
map[0]--;
}
int256[][] public unfilled = [
[int256(7), int256(0x6050403020100)],
[int256(11), int256(0xa09080706050403020100)],
[int256(15), int256(0xe0d0c0b0a09080706050403020100)],
[int256(11), int256(0x0b0a090807060403020100)], // iq
[int256(12), int256(0xc0b0a090807060504030201)], // partner
[int256(10), int256(0x9080706050403020100)],
[int256(11), int256(0x0a09080706050403020100)], // Portfolio
[int256(9), int256(0x080706050403020100)], // race
[int256(2), int256(0x100)],
[int256(13), int256(0x0c0b0a09080706050403020100)], // special
[int256(13), int256(0x0c0b0a09080706050403020100)] // weight
];
uint8[] private unfilledSpecialOverrides = [
9, // race0
10, // race1
11, // race2
13, // weight0
14, // weight1
0, // PARTNERS0
5, // IQ0
12, // IQ1
11, // Portfolio0
12, // Portfolio1
13, // Portfolio2
14, // Portfolio3
13, // Special0
14 // Special1
];
function calcIndex(AttributeType attr, uint256 kindex)
public
view
returns (uint256)
{
return uint256(getByte(unfilled[uint256(attr)][1], kindex));
}
function getAttributeValueByRange(AttributeType attr, uint256 tokenId)
internal
view
returns (uint8)
{
if (tokenId >= 8666 && tokenId < 8671 && attr == AttributeType.Race) {
return unfilledSpecialOverrides[0];
} else if (
tokenId >= 2103 && tokenId < 2108 && attr == AttributeType.Race
) {
return unfilledSpecialOverrides[1];
} else if (
tokenId >= 6666 && tokenId < 6668 && attr == AttributeType.Race
) {
return unfilledSpecialOverrides[2];
} else if (
tokenId >= 4520 && tokenId < 4530 && attr == AttributeType.Weight
) {
return unfilledSpecialOverrides[3];
} else if (
tokenId >= 250 && tokenId < 255 && attr == AttributeType.Weight
) {
return unfilledSpecialOverrides[4];
} else if (
tokenId >= 149 && tokenId < 159 && attr == AttributeType.Partner
) {
return unfilledSpecialOverrides[5];
} else if (tokenId >= 5295 && tokenId < 5296 && attr == AttributeType.IQ) {
return unfilledSpecialOverrides[6];
} else if (tokenId >= 1337 && tokenId < 1338 && attr == AttributeType.IQ) {
return unfilledSpecialOverrides[7];
} else if (
tokenId >= 48 && tokenId < 53 && attr == AttributeType.Portfolio
) {
return unfilledSpecialOverrides[8];
} else if (
tokenId >= 9002 && tokenId < 9006 && attr == AttributeType.Portfolio
) {
return unfilledSpecialOverrides[9];
} else if (
tokenId >= 5555 && tokenId < 5557 && attr == AttributeType.Portfolio
) {
return unfilledSpecialOverrides[10];
} else if (
tokenId >= 1338 && tokenId < 1339 && attr == AttributeType.Portfolio
) {
return unfilledSpecialOverrides[11];
} else if (
tokenId >= 4520 && tokenId < 4530 && attr == AttributeType.Special
) {
return unfilledSpecialOverrides[12];
} else if (
tokenId >= 250 && tokenId < 255 && attr == AttributeType.Special
) {
return unfilledSpecialOverrides[13];
} else {
return 0xff;
}
}
function generateAttributeForNewToken(AttributeType attr, uint256 tokenId)
internal
{
uint256[3][] storage _array = getArrayByAttr(attr);
uint8 sattr = getAttributeValueByRange(attr, tokenId);
if (sattr != 0xff) {
setAttributeOfToken(tokenId, attr, sattr);
_array[sattr][1]++;
return;
}
uint8 kindex = uint8(
random(uint256(unfilled[uint256(attr)][0] - 1), tokenId)
);
uint256 index = uint256(getByte(unfilled[uint256(attr)][1], kindex));
setAttributeOfToken(tokenId, attr, uint8(index));
_array[index][1]++;
if (_array[index][1] == _array[index][2]) {
removeUnfilled(unfilled[uint256(attr)], kindex);
}
}
function randomId() public view returns (uint256) {
return random(totalForUsers - 1, block.number);
}
function generateToken(uint256 tokenId) internal {
generateAttributeForNewToken(AttributeType.Age, tokenId);
generateAttributeForNewToken(AttributeType.Handicap, tokenId);
generateAttributeForNewToken(AttributeType.Height, tokenId);
generateAttributeForNewToken(AttributeType.IQ, tokenId);
generateAttributeForNewToken(AttributeType.Partner, tokenId);
generateAttributeForNewToken(AttributeType.Penis, tokenId);
generateAttributeForNewToken(AttributeType.Portfolio, tokenId);
generateAttributeForNewToken(AttributeType.Race, tokenId);
generateAttributeForNewToken(AttributeType.Sex, tokenId);
generateAttributeForNewToken(AttributeType.Special, tokenId);
generateAttributeForNewToken(AttributeType.Weight, tokenId);
}
function _safeMint(address to, uint256 tokenId) internal override {
// require(isInit, "Admin haven't init yet");
super._safeMint(to, tokenId);
generateToken(tokenId);
}
function exists(uint256 tokenId) public view returns (bool) {
return _exists(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(_exists(tokenId), "No such token");
string[23] memory parts;
parts[
0
] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = getAge(tokenId);
parts[2] = '</text><text x="10" y="40" class="base">';
parts[3] = getSex(tokenId);
parts[4] = '</text><text x="10" y="60" class="base">';
parts[5] = getRace(tokenId);
parts[6] = '</text><text x="10" y="80" class="base">';
parts[7] = getHeight(tokenId);
parts[8] = '</text><text x="10" y="100" class="base">';
parts[9] = getWeight(tokenId);
parts[10] = '</text><text x="10" y="120" class="base">';
parts[11] = getPenis(tokenId);
parts[12] = '</text><text x="10" y="140" class="base">';
parts[13] = getPartner(tokenId);
parts[14] = '</text><text x="10" y="160" class="base">';
parts[15] = getIQ(tokenId);
parts[16] = '</text><text x="10" y="180" class="base">';
parts[17] = getPortfolio(tokenId);
parts[18] = '</text><text x="10" y="200" class="base">';
parts[19] = getSpecialTalent(tokenId);
parts[20] = '</text><text x="10" y="220" class="base">';
parts[21] = getHandicap(tokenId);
parts[22] = "</text></svg>";
string memory output = string(
abi.encodePacked(
parts[0],
parts[1],
parts[2],
parts[3],
parts[4],
parts[5],
parts[6],
parts[7],
parts[8]
)
);
output = string(
abi.encodePacked(
output,
parts[9],
parts[10],
parts[11],
parts[12],
parts[13],
parts[14],
parts[15],
parts[16]
)
);
output = string(
abi.encodePacked(
output,
parts[17],
parts[18],
parts[19],
parts[20],
parts[21],
parts[22]
)
);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Anon #',
toString(tokenId),
'",',
'"attributes": [',
attributesToJson(tokenId),
'],"description": "NonFungibleYou are randomized anons generated and stored on chain. Feel free to use NonFungibleYou in any way you want.", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(abi.encodePacked("data:application/json;base64,", json));
return output;
}
function hasBonusToken(address addr) public view returns (bool) {
return bonusToken.balanceOf(addr) > 0;
}
function isWhitelisted(address addr) public view returns (bool) {
return !bonusUsed[addr] && hasBonusToken(addr);
}
function claim(uint256 tokenId) public payable nonReentrant {
require(tokenId > 0 && tokenId <= totalForUsers, "Token ID invalid");
if (isWhitelisted(msg.sender)) {
bonusUsed[msg.sender] = true;
} else {
require(msg.value == mintPrice, "Mint fee is not provided");
}
_safeMint(_msgSender(), tokenId);
}
function setMintPrice(uint256 newPrice) public onlyOwner nonReentrant {
mintPrice = newPrice;
}
function withdraw() public payable onlyOwner nonReentrant {
payable(owner()).transfer(address(this).balance);
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(
tokenId > totalForUsers && tokenId <= totalForOwner,
"Token ID invalid"
);
_safeMint(owner(), tokenId);
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(
out,
and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF)
)
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
| * @dev Collection of functions related to the address type/ | library Address {
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
(bool success, ) = recipient.call{ value: amount }("");
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"
);
require(isContract(target), "Address: call to non-contract");
return _verifyCallResult(success, returndata, errorMessage);
}
(bool success, bytes memory returndata) = target.call{ value: value }(data);
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
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;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
revert(errorMessage);
}
}
}
} else {
}
| 15,389,813 | [
1,
2532,
434,
4186,
3746,
358,
326,
1758,
618,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
5267,
288,
203,
97,
203,
225,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
565,
2254,
5034,
963,
31,
203,
565,
19931,
288,
203,
1377,
963,
519,
1110,
7000,
554,
12,
4631,
13,
203,
565,
289,
203,
565,
327,
963,
405,
374,
31,
203,
225,
289,
203,
203,
225,
445,
353,
8924,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
203,
565,
2254,
5034,
963,
31,
203,
565,
19931,
288,
203,
1377,
963,
519,
1110,
7000,
554,
12,
4631,
13,
203,
565,
289,
203,
565,
327,
963,
405,
374,
31,
203,
225,
289,
203,
203,
225,
445,
1366,
620,
12,
2867,
8843,
429,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
565,
2583,
12,
2867,
12,
2211,
2934,
12296,
1545,
3844,
16,
315,
1887,
30,
2763,
11339,
11013,
8863,
203,
203,
565,
2583,
12,
203,
1377,
2216,
16,
203,
1377,
315,
1887,
30,
13496,
358,
1366,
460,
16,
8027,
2026,
1240,
15226,
329,
6,
203,
565,
11272,
203,
225,
289,
203,
203,
565,
261,
6430,
2216,
16,
262,
273,
8027,
18,
1991,
95,
460,
30,
3844,
289,
2932,
8863,
203,
225,
445,
445,
1477,
12,
2867,
1018,
16,
1731,
3778,
501,
13,
203,
565,
2713,
203,
565,
1135,
261,
3890,
3778,
13,
203,
225,
288,
203,
565,
327,
445,
1477,
12,
3299,
16,
501,
16,
315,
1887,
30,
4587,
17,
2815,
745,
2535,
8863,
203,
225,
289,
203,
203,
225,
445,
445,
1477,
12,
203,
565,
1758,
1018,
16,
203,
2
] |
//Address: 0xA4F902f57Fd9FFcedF4dE6cF7EbC86ea9F76B5d1
//Contract name: EtheraffleICO
//Balance: 7.348300000000000094 Ether
//Verification Date: 3/7/2018
//Transacion Count: 28
// CODE STARTS HERE
pragma solidity^0.4.15;
contract EtheraffleLOT {
function mint(address _to, uint _amt) external {}
function transfer(address to, uint value) public {}
function balanceOf(address who) constant public returns (uint) {}
}
contract EtheraffleICO is EtheraffleLOT {
/* Lot reward per ether in each tier */
uint public constant tier0LOT = 110000 * 10 ** 6;
uint public constant tier1LOT = 100000 * 10 ** 6;
uint public constant tier2LOT = 90000 * 10 ** 6;
uint public constant tier3LOT = 80000 * 10 ** 6;
/* Bonus tickets multiplier */
uint public constant bonusLOT = 1500 * 10 ** 6;
uint public constant bonusFreeLOT = 10;
/* Maximum amount of ether investable per tier */
uint public constant maxWeiTier0 = 700 * 10 ** 18;
uint public constant maxWeiTier1 = 2500 * 10 ** 18;
uint public constant maxWeiTier2 = 7000 * 10 ** 18;
uint public constant maxWeiTier3 = 20000 * 10 ** 18;
/* Minimum investment (0.025 Ether) */
uint public constant minWei = 25 * 10 ** 15;
/* Crowdsale open, close, withdraw & tier times (UTC Format)*/
uint public ICOStart = 1522281600;//Thur 29th March 2018
uint public tier1End = 1523491200;//Thur 12th April 2018
uint public tier2End = 1525305600;//Thur 3rd May 2018
uint public tier3End = 1527724800;//Thur 31st May 2018
uint public wdBefore = 1528934400;//Thur 14th June 2018
/* Variables to track amount of purchases in tier */
uint public tier0Total;
uint public tier1Total;
uint public tier2Total;
uint public tier3Total;
/* Etheraffle's multisig wallet & LOT token addresses */
address public etheraffle;
/* ICO status toggle */
bool public ICORunning = true;
/* Map of purchaser's ethereum addresses to their purchase amounts for calculating bonuses*/
mapping (address => uint) public tier0;
mapping (address => uint) public tier1;
mapping (address => uint) public tier2;
mapping (address => uint) public tier3;
/* Instantiate the variables to hold Etheraffle's LOT & freeLOT token contract instances */
EtheraffleLOT LOT;
EtheraffleLOT FreeLOT;
/* Event loggers */
event LogTokenDeposit(address indexed from, uint value, bytes data);
event LogRefund(address indexed toWhom, uint amountOfEther, uint atTime);
event LogEtherTransfer(address indexed toWhom, uint amount, uint atTime);
event LogBonusLOTRedemption(address indexed toWhom, uint lotAmount, uint atTime);
event LogLOTTransfer(address indexed toWhom, uint indexed inTier, uint ethAmt, uint LOTAmt, uint atTime);
/**
* @dev Modifier function to prepend to later functions in this contract in
* order to redner them only useable by the Etheraffle address.
*/
modifier onlyEtheraffle() {
require(msg.sender == etheraffle);
_;
}
/**
* @dev Modifier function to prepend to later functions rendering the method
* only callable if the crowdsale is running.
*/
modifier onlyIfRunning() {
require(ICORunning);
_;
}
/**
* @dev Modifier function to prepend to later functions rendering the method
* only callable if the crowdsale is NOT running.
*/
modifier onlyIfNotRunning() {
require(!ICORunning);
_;
}
/**
* @dev Constructor. Sets up the variables pertaining to the ICO start &
* end times, the tier start & end times, the Etheraffle MultiSig Wallet
* address & the Etheraffle LOT & FreeLOT token contracts.
*/
function EtheraffleICO() public {//address _LOT, address _freeLOT, address _msig) public {
etheraffle = 0x97f535e98cf250cdd7ff0cb9b29e4548b609a0bd;
LOT = EtheraffleLOT(0xAfD9473dfe8a49567872f93c1790b74Ee7D92A9F);
FreeLOT = EtheraffleLOT(0xc39f7bB97B31102C923DaF02bA3d1bD16424F4bb);
}
/**
* @dev Purchase LOT tokens.
* LOT are sent in accordance with how much ether is invested, and in what
* tier the investment was made. The function also stores the amount of ether
* invested for later conversion to the amount of bonus LOT owed. Once the
* crowdsale is over and the final number of tokens sold is known, the purchaser's
* bonuses can be calculated. Using the fallback function allows LOT purchasers to
* simply send ether to this address in order to purchase LOT, without having
* to call a function. The requirements also also mean that once the crowdsale is
* over, any ether sent to this address by accident will be returned to the sender
* and not lost.
*/
function () public payable onlyIfRunning {
/* Requires the crowdsale time window to be open and the function caller to send ether */
require
(
now <= tier3End &&
msg.value >= minWei
);
uint numLOT = 0;
if (now <= ICOStart) {// ∴ tier zero...
/* Eth investable in each tier is capped via this requirement */
require(tier0Total + msg.value <= maxWeiTier0);
/* Store purchasers purchased amount for later bonus redemption */
tier0[msg.sender] += msg.value;
/* Track total investment in tier one for later bonus calculation */
tier0Total += msg.value;
/* Number of LOT this tier's purchase results in */
numLOT = (msg.value * tier0LOT) / (1 * 10 ** 18);
/* Transfer the number of LOT bought to the purchaser */
LOT.transfer(msg.sender, numLOT);
/* Log the transfer */
LogLOTTransfer(msg.sender, 0, msg.value, numLOT, now);
return;
} else if (now <= tier1End) {// ∴ tier one...
require(tier1Total + msg.value <= maxWeiTier1);
tier1[msg.sender] += msg.value;
tier1Total += msg.value;
numLOT = (msg.value * tier1LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 1, msg.value, numLOT, now);
return;
} else if (now <= tier2End) {// ∴ tier two...
require(tier2Total + msg.value <= maxWeiTier2);
tier2[msg.sender] += msg.value;
tier2Total += msg.value;
numLOT = (msg.value * tier2LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 2, msg.value, numLOT, now);
return;
} else {// ∴ tier three...
require(tier3Total + msg.value <= maxWeiTier3);
tier3[msg.sender] += msg.value;
tier3Total += msg.value;
numLOT = (msg.value * tier3LOT) / (1 * 10 ** 18);
LOT.transfer(msg.sender, numLOT);
LogLOTTransfer(msg.sender, 3, msg.value, numLOT, now);
return;
}
}
/**
* @dev Redeem bonus LOT: This function cannot be called until
* the crowdsale is over, nor after the withdraw period.
* During this window, a LOT purchaser calls this function
* in order to receive their bonus LOT owed to them, as
* calculated by their share of the total amount of LOT
* sales in the tier(s) following their purchase. Once
* claimed, user's purchased amounts are set to 1 wei rather
* than zero, to allow the contract to maintain a list of
* purchasers in each. All investors, regardless of tier/amount,
* receive ten free entries into the flagship Saturday
* Etheraffle via the FreeLOT coupon.
*/
function redeemBonusLot() external onlyIfRunning { //81k gas
/* Requires crowdsale to be over and the wdBefore time to not have passed yet */
require
(
now > tier3End &&
now < wdBefore
);
/* Requires user to have a LOT purchase in at least one of the tiers. */
require
(
tier0[msg.sender] > 1 ||
tier1[msg.sender] > 1 ||
tier2[msg.sender] > 1 ||
tier3[msg.sender] > 1
);
uint bonusNumLOT;
/* If purchaser has ether in this tier, LOT tokens owed is calculated and added to LOT amount */
if(tier0[msg.sender] > 1) {
bonusNumLOT +=
/* Calculate share of bonus LOT user is entitled to, based on tier one sales */
((tier1Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) +
/* Calculate share of bonus LOT user is entitled to, based on tier two sales */
((tier2Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18))) +
/* Calculate share of bonus LOT user is entitled to, based on tier three sales */
((tier3Total * bonusLOT * tier0[msg.sender]) / (tier0Total * (1 * 10 ** 18)));
/* Set amount of ether in this tier to 1 to make further bonus redemptions impossible */
tier0[msg.sender] = 1;
}
if(tier1[msg.sender] > 1) {
bonusNumLOT +=
((tier2Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18))) +
((tier3Total * bonusLOT * tier1[msg.sender]) / (tier1Total * (1 * 10 ** 18)));
tier1[msg.sender] = 1;
}
if(tier2[msg.sender] > 1) {
bonusNumLOT +=
((tier3Total * bonusLOT * tier2[msg.sender]) / (tier2Total * (1 * 10 ** 18)));
tier2[msg.sender] = 1;
}
if(tier3[msg.sender] > 1) {
tier3[msg.sender] = 1;
}
/* Final check that user cannot withdraw twice */
require
(
tier0[msg.sender] <= 1 &&
tier1[msg.sender] <= 1 &&
tier2[msg.sender] <= 1 &&
tier3[msg.sender] <= 1
);
/* Transfer bonus LOT to bonus redeemer */
if(bonusNumLOT > 0) {
LOT.transfer(msg.sender, bonusNumLOT);
}
/* Mint FreeLOT and give to bonus redeemer */
FreeLOT.mint(msg.sender, bonusFreeLOT);
/* Log the bonus LOT redemption */
LogBonusLOTRedemption(msg.sender, bonusNumLOT, now);
}
/**
* @dev Should crowdsale be cancelled for any reason once it has
* begun, any ether is refunded to the purchaser by calling
* this funcion. Function checks each tier in turn, totalling
* the amount whilst zeroing the balance, and finally makes
* the transfer.
*/
function refundEther() external onlyIfNotRunning {
uint amount;
if(tier0[msg.sender] > 1) {
/* Add balance of caller's address in this tier to the amount */
amount += tier0[msg.sender];
/* Zero callers balance in this tier */
tier0[msg.sender] = 0;
}
if(tier1[msg.sender] > 1) {
amount += tier1[msg.sender];
tier1[msg.sender] = 0;
}
if(tier2[msg.sender] > 1) {
amount += tier2[msg.sender];
tier2[msg.sender] = 0;
}
if(tier3[msg.sender] > 1) {
amount += tier3[msg.sender];
tier3[msg.sender] = 0;
}
/* Final check that user cannot be refunded twice */
require
(
tier0[msg.sender] == 0 &&
tier1[msg.sender] == 0 &&
tier2[msg.sender] == 0 &&
tier3[msg.sender] == 0
);
/* Transfer the ether to the caller */
msg.sender.transfer(amount);
/* Log the refund */
LogRefund(msg.sender, amount, now);
return;
}
/**
* @dev Function callable only by Etheraffle's multi-sig wallet. It
* transfers the tier's raised ether to the etheraffle multisig wallet
* once the tier is over.
*
* @param _tier The tier from which the withdrawal is being made.
*/
function transferEther(uint _tier) external onlyIfRunning onlyEtheraffle {
if(_tier == 0) {
/* Require tier zero to be over and a tier zero ether be greater than 0 */
require(now > ICOStart && tier0Total > 0);
/* Transfer the tier zero total to the etheraffle multisig */
etheraffle.transfer(tier0Total);
/* Log the transfer event */
LogEtherTransfer(msg.sender, tier0Total, now);
return;
} else if(_tier == 1) {
require(now > tier1End && tier1Total > 0);
etheraffle.transfer(tier1Total);
LogEtherTransfer(msg.sender, tier1Total, now);
return;
} else if(_tier == 2) {
require(now > tier2End && tier2Total > 0);
etheraffle.transfer(tier2Total);
LogEtherTransfer(msg.sender, tier2Total, now);
return;
} else if(_tier == 3) {
require(now > tier3End && tier3Total > 0);
etheraffle.transfer(tier3Total);
LogEtherTransfer(msg.sender, tier3Total, now);
return;
} else if(_tier == 4) {
require(now > tier3End && this.balance > 0);
etheraffle.transfer(this.balance);
LogEtherTransfer(msg.sender, this.balance, now);
return;
}
}
/**
* @dev Function callable only by Etheraffle's multi-sig wallet.
* It transfers any remaining unsold LOT tokens to the
* Etheraffle multisig wallet. Function only callable once
* the withdraw period and ∴ the ICO ends.
*/
function transferLOT() onlyEtheraffle onlyIfRunning external {
require(now > wdBefore);
uint amt = LOT.balanceOf(this);
LOT.transfer(etheraffle, amt);
LogLOTTransfer(msg.sender, 5, 0, amt, now);
}
/**
* @dev Toggle crowdsale status. Only callable by the Etheraffle
* mutlisig account. If set to false, the refund function
* becomes live allow purchasers to withdraw their ether
*
*/
function setCrowdSaleStatus(bool _status) external onlyEtheraffle {
ICORunning = _status;
}
/**
* @dev This function is what allows this contract to receive ERC223
* compliant tokens. Any tokens sent to this address will fire off
* an event announcing their arrival. Unlike ERC20 tokens, ERC223
* tokens cannot be sent to contracts absent this function,
* thereby preventing loss of tokens by mistakenly sending them to
* contracts not designed to accept them.
*
* @param _from From whom the transfer originated
* @param _value How many tokens were sent
* @param _data Transaction metadata
*/
function tokenFallback(address _from, uint _value, bytes _data) public {
if (_value > 0) {
LogTokenDeposit(_from, _value, _data);
}
}
/**
* @dev Housekeeping function in the event this contract is no
* longer needed. Will delete the code from the blockchain.
*/
function selfDestruct() external onlyIfNotRunning onlyEtheraffle {
selfdestruct(etheraffle);
}
}
| Transfer bonus LOT to bonus redeemer */ | if(bonusNumLOT > 0) {
LOT.transfer(msg.sender, bonusNumLOT);
require
}
| 13,066,143 | [
1,
5912,
324,
22889,
1806,
56,
358,
324,
22889,
283,
24903,
264,
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
] | [
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,
3639,
309,
12,
18688,
407,
2578,
1502,
56,
405,
374,
13,
288,
203,
5411,
1806,
56,
18,
13866,
12,
3576,
18,
15330,
16,
324,
22889,
2578,
1502,
56,
1769,
203,
3639,
2583,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 F3Devents {
// 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
);
// (fomo3d short only) 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
);
// (fomo3d short only) 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 F3Devents {}
contract FoMo3DLightning is modularShort {
using SafeMath for *;
using NameFilter for string;
using F3DKeysCalcShort for uint256;
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xb57371379e8BF49d3c0a8A07638E429386A636A4);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
address private admin = msg.sender;
string constant public name = "FOMO Lightning";
string constant public symbol = "LTNG";
uint256 private rndExtra_ = 15 minutes; // length of the very first ICO
uint256 private rndGap_ = 15 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 15 minutes; // round timer starts at this
uint256 constant private rndInc_ = 10 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 30 minutes; // 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 => F3Ddatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => F3Ddatasets.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 => F3Ddatasets.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 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => F3Ddatasets.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
// (F3D, P3D) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = F3Ddatasets.TeamFee(49,2); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = F3Ddatasets.TeamFee(49,2); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = F3Ddatasets.TeamFee(49,2); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = F3Ddatasets.TeamFee(49,2); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (F3D, P3D)
potSplit_[0] = F3Ddatasets.PotSplit(38,2); //48% to winner, 10% to next round, 2% to com
potSplit_[1] = F3Ddatasets.PotSplit(38,2); //48% to winner, 10% to next round, 2% to com
potSplit_[2] = F3Ddatasets.PotSplit(38,2); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = F3Ddatasets.PotSplit(38,2); //48% to winner, 10% to next round, 2% 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. check ?eta in discord");
_;
}
/**
* @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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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
F3Ddatasets.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 F3Devents.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 F3Devents.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 F3Devents.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 F3Devents.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 F3Devents.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, F3Ddatasets.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 F3Devents.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, F3Ddatasets.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 F3Devents.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, F3Ddatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 2100000000000000000)
{
uint256 _availableLimit = (2100000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// 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(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.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, F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.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(F3Ddatasets.EventReturns memory _eventData_)
private
returns (F3Ddatasets.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; //48%
uint256 _com = (_pot / 50); //2%
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
admin.transfer(_com);
admin.transfer(_p3d.sub(_p3d / 2));
round_[_rID].pot = _pot.add(_p3d / 2);
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// 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, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// pay 3% out to community rewards
uint256 _p1 = _eth / 100; //1%
uint256 _com = _eth / 50; //2%
_com = _com.add(_p1); //1 + 2 = 3
uint256 _p3d;
if (!address(admin).call.value(_com)())
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// 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 F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to divies contract
uint256 _potAmount = _p3d / 2;
admin.transfer(_p3d.sub(_potAmount));
round_[_rID].pot = round_[_rID].pot.add(_potAmount);
// set up event data
_eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit F3Devents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_)
private
returns(F3Ddatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
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(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 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, F3Ddatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit F3Devents.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 == admin);
// can only be ran once
require(activated_ == false);
// activate the contract
activated_ = true;
// lets start first round
rID_ = 1;
round_[1].strt = now + rndExtra_ - rndGap_;
round_[1].end = now + rndInit_ + rndExtra_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library F3Ddatasets {
//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 F3DKeysCalcShort {
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(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @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 ((78125000).mul(_keys.sq()).add(((149999843750000).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 withdraws all of your earnings. -functionhash- 0x3ccfd60b/ setup local rID grab time fetch player ID setup temp var for player eth check to see if round has ended and no one has run round end yet set up our tx event data end the round (distributes pot) get their earnings gib moni build event data fire withdraw and distribute event in any other situation get their earnings gib moni fire withdraw event | function withdraw()
isActivated()
isHuman()
public
{
uint256 _rID = rID_;
uint256 _now = now;
uint256 _pID = pIDxAddr_[msg.sender];
uint256 _eth;
if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0)
{
F3Ddatasets.EventReturns memory _eventData_;
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit F3Devents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.P3DAmount,
_eventData_.genAmount
);
_eth = withdrawEarnings(_pID);
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
| 29,080 | [
1,
1918,
9446,
87,
777,
434,
3433,
425,
1303,
899,
18,
300,
915,
2816,
17,
374,
92,
23,
952,
8313,
4848,
70,
19,
3875,
1191,
436,
734,
11086,
813,
2158,
7291,
1599,
3875,
1906,
569,
364,
7291,
13750,
866,
358,
2621,
309,
3643,
711,
16926,
471,
1158,
1245,
711,
1086,
3643,
679,
4671,
444,
731,
3134,
2229,
871,
501,
679,
326,
3643,
261,
2251,
1141,
5974,
13,
336,
3675,
425,
1303,
899,
314,
495,
6921,
77,
1361,
871,
501,
4452,
598,
9446,
471,
25722,
871,
316,
1281,
1308,
20886,
336,
3675,
425,
1303,
899,
314,
495,
6921,
77,
4452,
598,
9446,
871,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
598,
9446,
1435,
203,
3639,
353,
28724,
1435,
203,
3639,
27803,
6925,
1435,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2254,
5034,
389,
86,
734,
273,
436,
734,
67,
31,
203,
203,
3639,
2254,
5034,
389,
3338,
273,
2037,
31,
203,
203,
3639,
2254,
5034,
389,
84,
734,
273,
293,
734,
92,
3178,
67,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
2254,
5034,
389,
546,
31,
203,
203,
3639,
309,
261,
67,
3338,
405,
3643,
67,
63,
67,
86,
734,
8009,
409,
597,
3643,
67,
63,
67,
86,
734,
8009,
3934,
422,
629,
597,
3643,
67,
63,
67,
86,
734,
8009,
1283,
86,
480,
374,
13,
203,
3639,
288,
203,
5411,
478,
23,
40,
21125,
18,
1133,
1356,
3778,
389,
2575,
751,
67,
31,
203,
203,
1082,
202,
2260,
67,
63,
67,
86,
734,
8009,
3934,
273,
638,
31,
203,
5411,
389,
2575,
751,
67,
273,
679,
11066,
24899,
2575,
751,
67,
1769,
203,
203,
5411,
389,
546,
273,
598,
9446,
41,
1303,
899,
24899,
84,
734,
1769,
203,
203,
5411,
309,
261,
67,
546,
405,
374,
13,
203,
7734,
293,
715,
86,
67,
63,
67,
84,
734,
8009,
4793,
18,
13866,
24899,
546,
1769,
203,
203,
5411,
389,
2575,
751,
27799,
15385,
751,
273,
389,
2575,
751,
27799,
15385,
751,
397,
261,
67,
3338,
380,
2130,
12648,
12648,
1769,
203,
5411,
389,
2575,
751,
27799,
15385,
5103,
273,
389,
2575,
751,
27799,
15385,
5103,
397,
389,
84,
734,
31,
203,
203,
5411,
3626,
478,
23,
758,
616,
87,
18,
2
] |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "hardhat/console.sol";
import "./Orange.sol";
/// @title A conotract to depoit and withdraw ETH
/// @author Chen-kuo Chou
/// @notice Depoits, withdraws and check ETH balance
/// @dev A simple bank that safely processes payments
contract Pool {
/// @dev Sets up intitial contract balance to be 0
uint256 totalContractBalance = 0;
/// @dev Returns ETH balance in wei
mapping(address => uint256) balances;
/// @dev Points to Orange.sol address
address public orange;
/// @dev Sets up Orange.sol address when deploy
/// @param orangeAddress deployed Orange.sol address
constructor(address orangeAddress) {
orange = orangeAddress;
}
/// @notice Gets the totle ETH in this pool
/// @return Returns totalContractBalance
function getContractBalance() public view returns (uint256) {
return totalContractBalance;
}
/// @notice User add ETH in this pool
/// @param amount ETH amount to add
/// @return True for successful transaction
function addBalance(uint256 amount) public payable returns (bool) {
balances[msg.sender] += amount;
totalContractBalance += amount;
return true;
}
/// @notice Returns user's ETH balance in this pool
/// @return Returns through mapping balances[]
function getBalance() public view returns (uint256) {
return balances[msg.sender];
}
/// @notice User add ETH in this pool
/// @param withdrawAmount ETH amount to add
function withdraw(uint256 withdrawAmount) public payable {
require(withdrawAmount <= getBalance(), "Overdrawn");
balances[msg.sender] -= withdrawAmount;
totalContractBalance -= withdrawAmount;
(bool sent, ) = msg.sender.call{value: withdrawAmount}("");
require(sent, "Failed to withdraw");
}
/// @notice User can buy Orange from this pool
/// @dev Buys Orange with user's ETH in this pool
/// @param swapAmount ETH amount to buy Orange tokens
/// @return success for successful transaction
function buyOrange(uint256 swapAmount) public returns (bool) {
require(swapAmount <= getBalance(), "Overdrawn");
balances[msg.sender] -= swapAmount;
totalContractBalance -= swapAmount;
Orange o = Orange(orange);
o.mint(msg.sender, swapAmount);
return true;
}
/// @dev fallback function
receive() external payable {}
}
| @dev Sets up intitial contract balance to be 0 @dev Returns ETH balance in wei @dev Points to Orange.sol address @dev Sets up Orange.sol address when deploy @param orangeAddress deployed Orange.sol address | constructor(address orangeAddress) {
orange = orangeAddress;
}
| 12,921,936 | [
1,
2785,
731,
509,
305,
649,
6835,
11013,
358,
506,
374,
225,
2860,
512,
2455,
11013,
316,
732,
77,
225,
22464,
358,
2965,
726,
18,
18281,
1758,
377,
11511,
731,
2965,
726,
18,
18281,
1758,
1347,
7286,
282,
578,
726,
1887,
19357,
2965,
726,
18,
18281,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3885,
12,
2867,
578,
726,
1887,
13,
288,
203,
3639,
578,
726,
273,
578,
726,
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,
-100,
-100,
-100,
-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;
contract ERC20Basic {
uint256 public totalSupply;
string public name;
string public symbol;
uint8 public decimals;
function balanceOf(address who) constant public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ExternalToken {
function burn(uint256 _value, bytes _data) public;
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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));
// 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) constant public returns (uint256 balance) {
return balances[_owner];
}
}
contract TokenReceiver {
function onTokenTransfer(address _from, uint256 _value, bytes _data) public;
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
contract AbstractSale is TokenReceiver, Pausable {
using SafeMath for uint256;
event BonusChange(uint256 bonus);
event RateChange(address token, uint256 rate);
event Purchase(address indexed buyer, address token, uint256 value, uint256 amount);
event Withdraw(address token, address to, uint256 value);
event Burn(address token, uint256 value, bytes data);
mapping (address => uint256) rates;
uint256 public bonus;
function onTokenTransfer(address _from, uint256 _value, bytes _data) whenNotPaused public {
onReceive(msg.sender, _from, _value, _data);
}
function() payable whenNotPaused public {
receiveWithData("");
}
function receiveWithData(bytes _data) payable whenNotPaused public {
onReceive(address(0), msg.sender, msg.value, _data);
}
function onReceive(address _token, address _from, uint256 _value, bytes _data) internal {
uint256 tokens = getAmount(_token, _value);
require(tokens > 0);
address buyer;
if (_data.length == 20) {
buyer = address(toBytes20(_data, 0));
} else {
require(_data.length == 0);
buyer = _from;
}
Purchase(buyer, _token, _value, tokens);
doPurchase(buyer, tokens);
}
function doPurchase(address buyer, uint256 amount) internal;
function toBytes20(bytes b, uint256 _start) pure internal returns (bytes20 result) {
require(_start + 20 <= b.length);
assembly {
let from := add(_start, add(b, 0x20))
result := mload(from)
}
}
function getAmount(address _token, uint256 _value) constant public returns (uint256) {
uint256 rate = getRate(_token);
require(rate > 0);
uint256 beforeBonus = _value.mul(rate);
return beforeBonus.add(beforeBonus.mul(bonus).div(100)).div(10**18);
}
function getRate(address _token) constant public returns (uint256) {
return rates[_token];
}
function setRate(address _token, uint256 _rate) onlyOwner public {
rates[_token] = _rate;
RateChange(_token, _rate);
}
function setBonus(uint256 _bonus) onlyOwner public {
bonus = _bonus;
BonusChange(_bonus);
}
function withdraw(address _token, address _to, uint256 _amount) onlyOwner public {
require(_to != address(0));
verifyCanWithdraw(_token, _to, _amount);
if (_token == address(0)) {
_to.transfer(_amount);
} else {
ERC20(_token).transfer(_to, _amount);
}
Withdraw(_token, _to, _amount);
}
function burnWithData(address _token, uint256 _amount, bytes _data) onlyOwner public {
ExternalToken(_token).burn(_amount, _data);
Burn(_token, _amount, _data);
}
function verifyCanWithdraw(address _token, address _to, uint256 _amount) internal {
}
}
contract Sale is AbstractSale {
ERC20 public token;
function Sale(address _token) public {
token = ERC20(_token);
}
function doPurchase(address buyer, uint256 amount) internal {
token.transfer(buyer, amount);
}
/**
* @dev It should not let owners transfer tokens to protect investors
*/
function verifyCanWithdraw(address _token, address _to, uint256 _amount) internal {
require(_token != address(token));
}
}
contract GoldeaSale is Sale {
address public btcToken;
uint256 public constant end = 1522540800;
uint256 public constant total = 200000000000000;
function GoldeaSale(address _token, address _btcToken) Sale(_token) public {
btcToken = _btcToken;
}
function changeParameters(uint256 _ethRate, uint256 _btcRate, uint256 _bonus) onlyOwner public {
setRate(address(0), _ethRate);
setRate(btcToken, _btcRate);
setBonus(_bonus);
}
function setBtcToken(address _btcToken) onlyOwner public {
btcToken = _btcToken;
}
function doPurchase(address buyer, uint256 amount) internal {
require(now < end);
super.doPurchase(buyer, amount);
}
function burn() onlyOwner public {
require(now >= end);
BurnableToken(token).burn(token.balanceOf(this));
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant public returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) 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));
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) constant public returns (uint256 remaining) {
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 success) {
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 success) {
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;
}
}
contract BurnableToken is StandardToken {
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint _value)
public
{
require(_value > 0);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
}
event Burn(address indexed burner, uint indexed value);
} | * @dev It should not let owners transfer tokens to protect investors/ | function verifyCanWithdraw(address _token, address _to, uint256 _amount) internal {
require(_token != address(token));
}
| 1,828,634 | [
1,
7193,
1410,
486,
2231,
25937,
7412,
2430,
358,
17151,
2198,
395,
1383,
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,
3929,
2568,
1190,
9446,
12,
2867,
389,
2316,
16,
1758,
389,
869,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
3639,
2583,
24899,
2316,
480,
1758,
12,
2316,
10019,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface WalletInterface {
event CallSuccess(
bool rolledBack,
address to,
uint256 value,
bytes data,
bytes returnData
);
event CallFailure(
address to,
uint256 value,
bytes data,
string revertReason
);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
// Use an array of Calls for executing generic batch calls.
struct Call {
address to;
uint96 value;
bytes data;
}
// Use an array of CallReturns for handling generic batch calls.
struct CallReturn {
bool ok;
bytes returnData;
}
struct ValueReplacement {
uint24 returnDataOffset;
uint8 valueLength;
uint16 callIndex;
}
struct DataReplacement {
uint24 returnDataOffset;
uint24 dataLength;
uint16 callIndex;
uint24 callDataOffset;
}
struct AdvancedCall {
address to;
uint96 value;
bytes data;
ValueReplacement[] replaceValue;
DataReplacement[] replaceData;
}
struct AdvancedCallReturn {
bool ok;
bytes returnData;
uint96 callValue;
bytes callData;
}
receive() external payable;
function execute(
Call[] calldata calls
) external returns (bool[] memory ok, bytes[] memory returnData);
function executeAdvanced(
AdvancedCall[] calldata calls
) external returns (AdvancedCallReturn[] memory callResults);
function simulate(
Call[] calldata calls
) external /* view */ returns (bool[] memory ok, bytes[] memory returnData);
function simulateAdvanced(
AdvancedCall[] calldata calls
) external /* view */ returns (AdvancedCallReturn[] memory callResults);
function claimOwnership(address owner) external;
function transferOwnership(address newOwner) external;
function cancelOwnershipTransfer() external;
function acceptOwnership() external;
function owner() external view returns (address);
function isOwner() external view returns (bool);
function isValidSignature(bytes32 digest, bytes memory signature) external view returns (bytes4);
function getImplementation() external view returns (address implementation);
function getVersion() external pure returns (uint256 version);
function initialize(address) external pure;
}
/**
* @dev Library for determining if a given account is a contract.
*/
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
}
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
}
/**
* @notice Smart wallet supporting batch calls, EIP-1271, and call simulations.
* In order to claim ownership of a given smart wallet, a signed message and
* associated proof must be submitted to the "MerkleWalletClaimer" contract.
* @author 0age
*/
contract SmartWallet is WalletInterface {
using Address for address;
// Skip over previously-used storage slots.
address private __DEPRECATED_SLOT_ONE__;
uint256 private __DEPRECATED_SLOT_TWO__;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// Store the current owner of the contract.
address internal _owner;
// Store the next potential owner of the contract.
address internal _newPotentialOwner;
// Only this contract may call `claimOwnership` to set the initial owner.
address public constant merkleWalletClaimer = address(
0xD8470a6d796d54F13f243A4cf1a890E65bF3670E
);
// The "upgrade beacon" tracks the current implementation contract address/
address internal constant _UPGRADE_BEACON = address(
0x000000000026750c571ce882B17016557279ADaa
);
uint256 internal constant _VERSION = 17;
/**
* @notice Enable receipt of Ether.
*/
receive() external payable override {}
/**
* @notice Execute an atomic batch of calls.
* Can only be called by the current owner.
* @param calls The calls to execute.
* @return ok The status of each call.
* @return returnData The returndata of each call.
*/
function execute(
Call[] calldata calls
) external override onlyOwner() returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire a CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _execute.
_selfCallContext = this.execute.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._execute.selector, calls
)
);
// Ensure that self-call context has been cleared.
if (!externalOk) {
delete _selfCallContext;
}
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CallSuccess(
!externalOk, // If another call failed this will have been rolled back
currentCall.to,
uint256(currentCall.value),
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
currentCall.to,
uint256(currentCall.value),
currentCall.data,
_decodeRevertReason(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @dev "Internal" helper to execute an atomic batch of calls.
* Can only be called from this contract during a call to `execute`.
* @param calls The calls to execute.
* @return callResults The results of each call.
*/
function _execute(
Call[] calldata calls
) external returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.execute.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call{
value: uint256(calls[i].value)
}(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
/**
* @notice Execute an atomic batch of advanced calls (where returndata can be used to
* populate calldata of subsequent calls). Can only be called by the current owner.
* @param calls The advanced calls to execute.
* @return callResults The results of each advanced call.
*/
function executeAdvanced(
AdvancedCall[] calldata calls
) external override onlyOwner() returns (AdvancedCallReturn[] memory callResults) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
callResults = new AdvancedCallReturn[](calls.length);
// Set self-call context to call _executeAdvanced.
_selfCallContext = this.executeAdvanced.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._executeAdvanced.selector, calls
)
);
// Note: there are more efficient ways to check for revert reasons.
if (
rawCallResults.length > 68 && // prefix (4) + position (32) + length (32)
rawCallResults[0] == bytes1(0x08) &&
rawCallResults[1] == bytes1(0xc3) &&
rawCallResults[2] == bytes1(0x79) &&
rawCallResults[3] == bytes1(0xa0)
) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Ensure that self-call context has been cleared.
if (!externalOk) {
delete _selfCallContext;
}
// Parse data returned from self-call into each call result and store / log.
callResults = abi.decode(rawCallResults, (AdvancedCallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
AdvancedCall memory currentCall = calls[i];
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed".
emit CallSuccess(
!externalOk, // If another call failed this will have been rolled back
currentCall.to,
uint256(callResults[i].callValue),
callResults[i].callData,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
currentCall.to,
uint256(callResults[i].callValue),
callResults[i].callData,
_decodeRevertReason(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @dev "Internal" helper to execute an atomic batch of advanced calls.
* Can only be called from this contract during a call to `executeAdvanced`.
* @param calls The advanced calls to execute.
* @return callResults The results of each advanced call.
*/
function _executeAdvanced(
AdvancedCall[] memory calls
) public returns (AdvancedCallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.executeAdvanced.selector);
bool rollBack = false;
callResults = new AdvancedCallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
AdvancedCall memory a = calls[i];
uint256 callValue = uint256(a.value);
bytes memory callData = a.data;
uint256 callIndex;
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = a.to.call{value: callValue}(callData);
callResults[i] = AdvancedCallReturn({
ok: ok,
returnData: returnData,
callValue: uint96(callValue),
callData: callData
});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
for (uint256 j = 0; j < a.replaceValue.length; j++) {
callIndex = uint256(a.replaceValue[j].callIndex);
// Note: this check could be performed prior to execution.
if (i >= callIndex) {
revert("Cannot replace value using call that has not yet been performed.");
}
uint256 returnOffset = uint256(a.replaceValue[j].returnDataOffset);
uint256 valueLength = uint256(a.replaceValue[j].valueLength);
// Note: this check could be performed prior to execution.
if (valueLength == 0 || valueLength > 32) {
revert("bad valueLength");
}
if (returnData.length < returnOffset + valueLength) {
revert("Return values are too short to give back a value at supplied index.");
}
AdvancedCall memory callTarget = calls[callIndex];
uint256 valueOffset = 32 - valueLength;
assembly {
returndatacopy(
add(add(callTarget, 32), valueOffset), returnOffset, valueLength
)
}
}
for (uint256 k = 0; k < a.replaceData.length; k++) {
callIndex = uint256(a.replaceData[k].callIndex);
// Note: this check could be performed prior to execution.
if (i >= callIndex) {
revert("Cannot replace data using call that has not yet been performed.");
}
uint256 callOffset = uint256(a.replaceData[k].callDataOffset);
uint256 returnOffset = uint256(a.replaceData[k].returnDataOffset);
uint256 dataLength = uint256(a.replaceData[k].dataLength);
if (returnData.length < returnOffset + dataLength) {
revert("Return values are too short to give back a value at supplied index.");
}
bytes memory callTargetData = calls[callIndex].data;
// Note: this check could be performed prior to execution.
if (callTargetData.length < callOffset + dataLength) {
revert("Calldata too short to insert returndata at supplied offset.");
}
assembly {
returndatacopy(
add(callTargetData, add(32, callOffset)), returnOffset, dataLength
)
}
}
}
if (rollBack) {
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
/**
* @notice Simulate an atomic batch of calls. Any state changes will be rolled back.
* @param calls The calls to simulate.
* @return ok The simulated status of each call.
* @return returnData The simulated returndata of each call.
*/
function simulate(
Call[] calldata calls
) external /* view */ override returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.simulate.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool mustBeFalse, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._simulate.selector, calls
)
);
// Note: this should never be the case, but check just to be extra safe.
if (mustBeFalse) {
revert("Simulation code must revert!");
}
// Ensure that self-call context has been cleared.
delete _selfCallContext;
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
if (!callResults[i].ok) {
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
/**
* @dev "Internal" helper to simulate an atomic batch of calls.
* Can only be called from this contract during a call to `simulate`.
* @param calls The calls to simulate.
* @return callResults The simulated results of each call.
*/
function _simulate(
Call[] calldata calls
) external returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.simulate.selector);
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call{
value: uint256(calls[i].value)
}(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
break;
}
}
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
/**
* @notice Simulate an atomic batch of advanced calls (where returndata can be used to
* populate calldata of subsequent calls). Any state changes will be rolled back.
* @param calls The advanced calls to simulate.
* @return callResults The simulated results of each advanced call.
*/
function simulateAdvanced(
AdvancedCall[] calldata calls
) external /* view */ override returns (AdvancedCallReturn[] memory callResults) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
if (calls[i].value == 0) {
_ensureValidGenericCallTarget(calls[i].to);
}
}
// Specify length of returned values in order to work with them in memory.
callResults = new AdvancedCallReturn[](calls.length);
// Set self-call context to call _simulateActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.simulateAdvanced.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool mustBeFalse, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._simulateAdvanced.selector, calls
)
);
// Note: this should never be the case, but check just to be extra safe.
if (mustBeFalse) {
revert("Simulation code must revert!");
}
// Note: there are more efficient ways to check for revert reasons.
if (
rawCallResults.length > 68 && // prefix (4) + position (32) + length (32)
rawCallResults[0] == bytes1(0x08) &&
rawCallResults[1] == bytes1(0xc3) &&
rawCallResults[2] == bytes1(0x79) &&
rawCallResults[3] == bytes1(0xa0)
) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
// Ensure that self-call context has been cleared.
delete _selfCallContext;
// Parse data returned from self-call into each call result and return.
callResults = abi.decode(rawCallResults, (AdvancedCallReturn[]));
}
/**
* @dev "Internal" helper to simulate an atomic batch of advanced calls.
* Can only be called from this contract during a call to `simulateAdvanced`.
* @param calls The advanced calls to simulate.
* @return callResults The simulated results of each advanced call.
*/
function _simulateAdvanced(
AdvancedCall[] calldata calls
) external /* view */ returns (AdvancedCallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.simulateAdvanced.selector);
callResults = new AdvancedCallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
AdvancedCall memory a = calls[i];
uint256 callValue = uint256(a.value);
bytes memory callData = a.data;
uint256 callIndex;
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = a.to.call{value: callValue}(callData);
callResults[i] = AdvancedCallReturn({
ok: ok,
returnData: returnData,
callValue: uint96(callValue),
callData: callData
});
if (!ok) {
// Exit early - any calls after the first failed call will not execute.
break;
}
for (uint256 j = 0; j < a.replaceValue.length; j++) {
callIndex = uint256(a.replaceValue[j].callIndex);
// Note: this check could be performed prior to execution.
if (i >= callIndex) {
revert("Cannot replace value using call that has not yet been performed.");
}
uint256 returnOffset = uint256(a.replaceValue[j].returnDataOffset);
uint256 valueLength = uint256(a.replaceValue[j].valueLength);
// Note: this check could be performed prior to execution.
if (valueLength == 0 || valueLength > 32) {
revert("bad valueLength");
}
if (returnData.length < returnOffset + valueLength) {
revert("Return values are too short to give back a value at supplied index.");
}
AdvancedCall memory callTarget = calls[callIndex];
uint256 valueOffset = 32 - valueLength;
assembly {
returndatacopy(
add(add(callTarget, 32), valueOffset), returnOffset, valueLength
)
}
}
for (uint256 k = 0; k < a.replaceData.length; k++) {
callIndex = uint256(a.replaceData[k].callIndex);
// Note: this check could be performed prior to execution.
if (i >= callIndex) {
revert("Cannot replace data using call that has not yet been performed.");
}
uint256 callOffset = uint256(a.replaceData[k].callDataOffset);
uint256 returnOffset = uint256(a.replaceData[k].returnDataOffset);
uint256 dataLength = uint256(a.replaceData[k].dataLength);
if (returnData.length < returnOffset + dataLength) {
revert("Return values are too short to give back a value at supplied index.");
}
bytes memory callTargetData = calls[callIndex].data;
// Note: this check could be performed prior to execution.
if (callTargetData.length < callOffset + dataLength) {
revert("Calldata too short to insert returndata at supplied offset.");
}
assembly {
returndatacopy(
add(callTargetData, add(32, callOffset)), returnOffset, dataLength
)
}
}
}
// Wrap in length encoding and revert (provide bytes instead of a string).
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
/**
* @notice Enable the MerkleWalletClaimer contract to assign an owner.
* No other caller is permitted.
* @param newOwner The owner to assign.
*/
function claimOwnership(address newOwner) external override {
require(
msg.sender == merkleWalletClaimer,
"Only the MerkleWalletClaimer contract can call this function."
);
require(
_owner == address(0),
"Cannot claim ownership with an owner already set."
);
require(newOwner != address(0), "New owner cannot be the zero address.");
_setOwner(newOwner);
}
/**
* @notice Allow a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
* @param newOwner the new potential owner.
*/
function transferOwnership(address newOwner) external override onlyOwner() {
require(
newOwner != address(0),
"transferOwnership: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @notice Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() external override onlyOwner() {
delete _newPotentialOwner;
}
/**
* @notice Transfer ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() external override {
require(
msg.sender == _newPotentialOwner,
"acceptOwnership: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
_setOwner(msg.sender);
}
/**
* @notice Returns the address of the current owner.
* @return The owner.
*/
function owner() external view override returns (address) {
return _owner;
}
/**
* @notice Returns true if the caller is the current owner.
* @return True if caller is the owner, else false.
*/
function isOwner() public view override returns (bool) {
return msg.sender == _owner;
}
/**
* @notice Implementation of EIP-1271.
* Should return whether the signature provided is valid for the provided data.
* @param digest Hash of a message signed on the behalf of address(this)
* @param signature Signature byte array associated with digest
* @return The EIP-1271 magic value on success, otherwise empty bytes.
*/
function isValidSignature(
bytes32 digest,
bytes memory signature
) external view returns (bytes4) {
return ECDSA.recover(digest, signature) == _owner
? this.isValidSignature.selector
: bytes4(0);
}
/**
* @notice View function for getting the current smart wallet
* implementation contract address set on the upgrade beacon.
* @return implementation The current smart wallet implementation contract.
*/
function getImplementation() external view override returns (address implementation) {
(bool ok, bytes memory returnData) = _UPGRADE_BEACON.staticcall("");
if (!(ok && returnData.length == 32)) {
revert("Could not retrieve implementation.");
}
implementation = abi.decode(returnData, (address));
}
/**
* @notice Pure function for getting the current version.
* @return version The current version.
*/
function getVersion() external pure override returns (uint256 version) {
version = _VERSION;
}
/**
* @notice Contract initialization is now a no-op.
*/
function initialize(address) external pure override {}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "caller is not the owner.");
_;
}
/**
* @dev Set the owner of this contract.
* @param newOwner The new owner to set for this contract.
*/
function _setOwner(address newOwner) internal {
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Ensure that calls to protected internal helpers originate from the
* correct source.
* @param selfCallContext The selector for the originating function.
*/
function _enforceSelfCallFrom(bytes4 selfCallContext) internal {
// Ensure caller is this contract and self-call context is correctly set.
if (msg.sender != address(this) || _selfCallContext != selfCallContext) {
revert("External accounts or unapproved internal functions cannot call this.");
}
// Clear the self-call context.
delete _selfCallContext;
}
/**
* @dev Ensure that calls specify a valid target.
* @param to The target account.
*/
function _ensureValidGenericCallTarget(address to) internal view {
if (!to.isContract()) {
revert("Invalid `to` parameter - must supply a contract address containing code.");
}
if (to == address(this)) {
revert("Invalid `to` parameter - cannot supply the address of this contract.");
}
}
/**
* @dev Decode revert reasons.
* @param revertData The undecoded returndata from the reverting call.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == bytes1(0x08) &&
revertData[1] == bytes1(0xc3) &&
revertData[2] == bytes1(0x79) &&
revertData[3] == bytes1(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = "(no revert reason)";
}
}
} | * @dev Set the owner of this contract. @param newOwner The new owner to set for this contract./ | function _setOwner(address newOwner) internal {
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
| 10,242,024 | [
1,
694,
326,
3410,
434,
333,
6835,
18,
225,
394,
5541,
1021,
394,
3410,
358,
444,
364,
333,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
389,
542,
5541,
12,
2867,
394,
5541,
13,
2713,
288,
203,
565,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
394,
5541,
1769,
203,
203,
565,
389,
8443,
273,
394,
5541,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xd8b132A0abA610D0AaA18716A2b26e14141f112C/sources/contracts/peer-to-pool/LoanProposalImpl.sol | the currentRepaymentIdx (initially 0) gets incremented on repay or if all lenders converted for given period; hence any `repaymentIdx` smaller than `currentRepaymentIdx` will always map to a valid repayment claim | function claimRepayment(uint256 repaymentIdx) external {
(address fundingPool, uint256 lenderContribution) = _checkIsLender();
if (repaymentIdx >= dynamicData.currentRepaymentIdx) {
revert Errors.RepaymentIdxTooLarge();
}
DataTypesPeerToPool.LoanStatus status = dynamicData.status;
if (
status != DataTypesPeerToPool.LoanStatus.LOAN_DEPLOYED &&
status != DataTypesPeerToPool.LoanStatus.DEFAULTED
) {
revert Errors.InvalidActionForCurrentStatus();
}
storage lenderClaimedRepaymentPerRepaymentIdx = _lenderClaimedRepayment[
msg.sender
];
if (
lenderClaimedRepaymentPerRepaymentIdx[repaymentIdx] ||
_lenderExercisedConversion[msg.sender][repaymentIdx]
) {
revert Errors.AlreadyClaimed();
}
totalConvertedSubscriptionsPerIdx[repaymentIdx];
uint256 claimAmount = (_loanTokenRepaid[repaymentIdx] *
lenderContribution) / subscriptionsEntitledToRepayment;
lenderClaimedRepaymentPerRepaymentIdx[repaymentIdx] = true;
IERC20Metadata(IFundingPoolImpl(fundingPool).depositToken())
.safeTransfer(msg.sender, claimAmount);
emit RepaymentClaimed(msg.sender, claimAmount, repaymentIdx);
}
| 17,176,341 | [
1,
5787,
783,
426,
9261,
4223,
261,
2738,
6261,
374,
13,
5571,
28859,
603,
2071,
528,
578,
309,
777,
328,
10130,
5970,
364,
864,
3879,
31,
20356,
1281,
1375,
266,
9261,
4223,
68,
10648,
2353,
1375,
2972,
426,
9261,
4223,
68,
903,
3712,
852,
358,
279,
923,
2071,
2955,
7516,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
426,
9261,
12,
11890,
5034,
2071,
2955,
4223,
13,
3903,
288,
203,
3639,
261,
2867,
22058,
2864,
16,
2254,
5034,
328,
2345,
442,
4027,
13,
273,
389,
1893,
2520,
48,
2345,
5621,
203,
3639,
309,
261,
266,
9261,
4223,
1545,
5976,
751,
18,
2972,
426,
9261,
4223,
13,
288,
203,
5411,
15226,
9372,
18,
426,
9261,
4223,
10703,
20020,
5621,
203,
3639,
289,
203,
3639,
1910,
2016,
6813,
774,
2864,
18,
1504,
304,
1482,
1267,
273,
5976,
751,
18,
2327,
31,
203,
3639,
309,
261,
203,
5411,
1267,
480,
1910,
2016,
6813,
774,
2864,
18,
1504,
304,
1482,
18,
1502,
1258,
67,
1639,
22971,
2056,
597,
203,
5411,
1267,
480,
1910,
2016,
6813,
774,
2864,
18,
1504,
304,
1482,
18,
1639,
2046,
1506,
6404,
203,
3639,
262,
288,
203,
5411,
15226,
9372,
18,
1941,
1803,
1290,
3935,
1482,
5621,
203,
3639,
289,
203,
5411,
2502,
328,
2345,
9762,
329,
426,
9261,
2173,
426,
9261,
4223,
273,
389,
80,
2345,
9762,
329,
426,
9261,
63,
203,
7734,
1234,
18,
15330,
203,
5411,
308,
31,
203,
3639,
309,
261,
203,
5411,
328,
2345,
9762,
329,
426,
9261,
2173,
426,
9261,
4223,
63,
266,
9261,
4223,
65,
747,
203,
5411,
389,
80,
2345,
424,
12610,
5918,
6814,
63,
3576,
18,
15330,
6362,
266,
9261,
4223,
65,
203,
3639,
262,
288,
203,
5411,
15226,
9372,
18,
9430,
9762,
329,
5621,
203,
3639,
289,
203,
5411,
2078,
22063,
15440,
2173,
4223,
63,
266,
9261,
4223,
15533,
203,
3639,
2254,
5034,
7516,
6275,
273,
261,
67,
383,
2
] |
pragma solidity ^0.4.15;
/**
* @title Safe math operations that throw error on overflow.
*
* Credit: Taking ideas from FirstBlood token
*/
library SafeMath {
/**
* @dev Safely add two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x+y.
*/
function add(uint256 x, uint256 y)
internal constant
returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
/**
* @dev Safely substract two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x-y.
*/
function sub(uint256 x, uint256 y)
internal constant
returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
/**
* @dev Safely multiply two numbers.
*
* @param x First operant.
* @param y Second operant.
* @return The result of x*y.
*/
function mul(uint256 x, uint256 y)
internal constant
returns(uint256) {
uint256 z = x * y;
assert((x == 0) || (z/x == y));
return z;
}
/**
* @dev Parse a floating point number from String to uint, e.g. "250.56" to "25056"
*/
function parse(string s)
internal constant
returns (uint256)
{
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) {
if (b[i] >= 48 && b[i] <= 57) {
result = result * 10 + (uint(b[i]) - 48);
}
}
return result;
}
}
/**
* @title The abstract ERC-20 Token Standard definition.
*
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract Token {
/// @dev Returns the total token supply.
uint256 public totalSupply;
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);
/// @dev MUST trigger when tokens are transferred, including zero value transfers.
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/// @dev MUST trigger on any successful call to approve(address _spender, uint256 _value).
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* @title Default implementation of the ERC-20 Token Standard.
*/
contract StandardToken is Token {
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/**
* @dev Transfers _value amount of tokens to address _to, and MUST fire the Transfer event.
* @dev The function SHOULD throw if the _from account balance does not have enough tokens to spend.
*
* @dev A token contract which creates new tokens SHOULD trigger a Transfer event with the _from address set to 0x0 when tokens are created.
*
* Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
*
* @param _to The receiver of the tokens.
* @param _value The amount of tokens to send.
* @return True on success, false otherwise.
*/
function transfer(address _to, uint256 _value)
public
returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
balances[_to] = SafeMath.add(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Transfers _value amount of tokens from address _from to address _to, and MUST fire the Transfer event.
*
* @dev The transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf.
* @dev This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in
* @dev sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of
* @dev the message via some mechanism.
*
* Note Transfers of 0 values MUST be treated as normal transfers and fire the Transfer event.
*
* @param _from The sender of the tokens.
* @param _to The receiver of the tokens.
* @param _value The amount of tokens to send.
* @return True on success, false otherwise.
*/
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) {
balances[_to] = SafeMath.add(balances[_to], _value);
balances[_from] = SafeMath.sub(balances[_from], _value);
allowed[_from][msg.sender] = SafeMath.sub(allowed[_from][msg.sender], _value);
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Returns the account balance of another account with address _owner.
*
* @param _owner The address of the account to check.
* @return The account balance.
*/
function balanceOf(address _owner)
public constant
returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Allows _spender to withdraw from your account multiple times, up to the _value amount.
* @dev If this function is called again it overwrites the current allowance with _value.
*
* @dev NOTE: To prevent attack vectors like the one described in [1] and discussed in [2], clients
* @dev SHOULD make sure to create user interfaces in such a way that they set the allowance first
* @dev to 0 before setting it to another value for the same spender. THOUGH The contract itself
* @dev shouldn't enforce it, to allow backwards compatilibilty with contracts deployed before.
* @dev [1] https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/
* @dev [2] 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.
* @return True on success, false otherwise.
*/
function approve(address _spender, uint256 _value)
public
onlyPayloadSize(2)
returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Returns the amount which _spender is still allowed to withdraw from _owner.
*
* @param _owner The address of the sender.
* @param _spender The address of the receiver.
* @return The allowed withdrawal amount.
*/
function allowance(address _owner, address _spender)
public constant
onlyPayloadSize(2)
returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
// <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.
*/
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() 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);
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) 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) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
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 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 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 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 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 returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal 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 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 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 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 returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
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, sha3(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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(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] = 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)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
function matchBytes32Prefix(bytes32 content, bytes prefix) internal returns (bool){
bool match_ = true;
for (var i=0; i<prefix.length; 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){
bool checkok;
// 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);
checkok = (sha3(keyhash) == sha3(sha256(context_name, queryId)));
if (checkok == false) 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)
checkok = matchBytes32Prefix(sha256(sig1), result);
if (checkok == false) return false;
// Step 4: commitment match verification, sha3(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] == sha3(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);
checkok = verifySig(sha256(tosign1), sig1, sessionPubkey);
if (checkok == false) 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 returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // 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 The EVNToken Token contract.
*
* Credit: Taking ideas from BAT token and NET token
*/
/*is StandardToken */
contract EVNToken is StandardToken, usingOraclize {
// Token metadata
string public constant name = "Envion";
string public constant symbol = "EVN";
uint256 public constant decimals = 18;
string public constant version = "0.9";
// Fundraising goals: minimums and maximums
uint256 public constant TOKEN_CREATION_CAP = 130 * (10**6) * 10**decimals; // 130 million EVNs
uint256 public constant TOKEN_CREATED_MIN = 1 * (10**6) * 10**decimals; // 1 million EVNs
uint256 public constant ETH_RECEIVED_CAP = 5333 * (10**2) * 10**decimals; // 533 300 ETH
uint256 public constant ETH_RECEIVED_MIN = 1 * (10**3) * 10**decimals; // 1 000 ETH
uint256 public constant TOKEN_MIN = 1 * 10**decimals; // 1 EVN
// Discount multipliers
uint256 public constant TOKEN_FIRST_DISCOUNT_MULTIPLIER = 142857; // later divided by 10^5 to give users 1,42857 times more tokens per ETH == 30% discount
uint256 public constant TOKEN_SECOND_DISCOUNT_MULTIPLIER = 125000; // later divided by 10^5 to give users 1,25 more tokens per ETH == 20% discount
uint256 public constant TOKEN_THIRD_DISCOUNT_MULTIPLIER = 111111; // later divided by 10^5 to give users 1,11111 more tokens per ETH == 10% discount
// Fundraising parameters provided when creating the contract
uint256 public fundingStartBlock; // These two blocks need to be chosen to comply with the
uint256 public fundingEndBlock; // start date and 31 day duration requirements
uint256 public roundTwoBlock; // block number that triggers the second exchange rate change
uint256 public roundThreeBlock; // block number that triggers the third exchange rate change
uint256 public roundFourBlock; // block number that triggers the fourth exchange rate change
uint256 public ccReleaseBlock; // block number that triggers purchases made by CC be transferable
address public admin1; // First administrator for multi-sig mechanism
address public admin2; // Second administrator for multi-sig mechanism
address public tokenVendor; // Account delivering Tokens purchased with credit card
// Contracts current state (Fundraising, Finalized, Paused) and the saved state (if currently paused)
ContractState public state; // Current state of the contract
ContractState private savedState; // State of the contract before pause
//@dev Usecase related: Purchasing Tokens with Credit card
//@dev Usecase related: Canceling purchases done with credit card
mapping (string => Purchase) purchases; // in case CC payments get charged back, admins shall only be allowed to kill the exact amount of tokens associated with this payment
mapping (address => uint256) public ccLockedUpBalances; // tracking the total amount of tokens users have bought via CC - locked up until ccReleaseBlock
string[] public purchaseArray; // holding the IDs of all CC purchases
// Keep track of holders and icoBuyers
mapping (address => bool) public isHolder; // track if a user is a known token holder to the smart contract - important for payouts later
address[] public holders; // array of all known holders - important for payouts later
mapping (address => bool) isIcoBuyer; // for tracking if user has to be kyc verified before being able to transfer tokens
// ETH balance per user
// Since we have different exchange rates at different stages, we need to keep track
// of how much ether each contributed in case that we need to issue a refund
mapping (address => uint256) private ethBalances;
mapping (address => uint256) private noKycEthBalances;
// Total received ETH balances
// We need to keep track of how much ether have been contributed, since we have a cap for ETH too
uint256 public allReceivedEth;
uint256 public allUnKycedEth; // total amount of ETH we have no KYC for yet
// store the hashes of admins' msg.data
mapping (address => bytes32) private multiSigHashes;
// KYC
mapping (address => bool) public isKycTeam; // to determine, if a user belongs to the KYC team or not
mapping (address => bool) public kycVerified; // to check if user has already undergone KYC or not, to lock up his tokens until then
// to track if team members already got their tokens
bool public teamTokensDelivered;
// Current ETH/USD exchange rate
uint256 public ETH_USD_EXCHANGE_RATE_IN_CENTS; // set by oraclize
// Everything oraclize related
event updatedPrice(string price);
event newOraclizeQuery(string description);
uint public oraclizeQueryCost;
// Events used for logging
event LogRefund(address indexed _to, uint256 _value);
event LogCreateEVN(address indexed _to, uint256 _value);
event LogDeliverEVN(address indexed _to, uint256 _value);
event LogCancelDelivery(address indexed _to, string _id);
event LogKycRefused(address indexed _user, uint256 _value);
event LogTeamTokensDelivered(address indexed distributor, uint256 _value);
// Additional helper structs
enum ContractState { Fundraising, Finalized, Paused }
// Credit Card Purchase Parameters
//@dev Usecase related: Purchase Tokens with Credit card
//@dev Usecase related: Cancel purchase done with credit card
struct Purchase {
address buyer;
uint256 tokenAmount;
bool active;
}
// Modifiers
modifier isFinalized() {
require(state == ContractState.Finalized);
_;
}
modifier isFundraising() {
require(state == ContractState.Fundraising);
_;
}
modifier isPaused() {
require(state == ContractState.Paused);
_;
}
modifier notPaused() {
require(state != ContractState.Paused);
_;
}
modifier isFundraisingIgnorePaused() {
require(state == ContractState.Fundraising || (state == ContractState.Paused && savedState == ContractState.Fundraising));
_;
}
modifier onlyKycTeam(){
require(isKycTeam[msg.sender] == true);
_;
}
modifier onlyOwner() {
// check if transaction sender is admin.
require (msg.sender == admin1 || msg.sender == admin2);
// if yes, store his msg.data.
multiSigHashes[msg.sender] = keccak256(msg.data);
// check if his stored msg.data hash equals to the one of the other admin
if ((multiSigHashes[admin1]) == (multiSigHashes[admin2])) {
// if yes, both admins agreed - continue.
_;
// Reset hashes after successful execution
multiSigHashes[admin1] = 0x0;
multiSigHashes[admin2] = 0x0;
} else {
// if not (yet), return.
return;
}
}
modifier onlyVendor() {
require(msg.sender == tokenVendor);
_;
}
modifier minimumReached() {
require(allReceivedEth >= ETH_RECEIVED_MIN);
require(totalSupply >= TOKEN_CREATED_MIN);
_;
}
modifier isKycVerified(address _user) {
// if token transferring user acquired the tokens through the ICO...
if (isIcoBuyer[_user] == true) {
// ...check if user is already unlocked
require (kycVerified[_user] == true);
}
_;
}
modifier hasEnoughUnlockedTokens(address _user, uint256 _value) {
// check if the user was a CC buyer and if the lockup period is not over,
if (ccLockedUpBalances[_user] > 0 && block.number < ccReleaseBlock) {
// allow to only transfer the not-locked up tokens
require ((SafeMath.sub(balances[_user], _value)) >= ccLockedUpBalances[_user]);
}
_;
}
/**
* @dev Create a new EVNToken contract.
*
* _fundingStartBlock The starting block of the fundraiser (has to be in the future).
* _fundingEndBlock The end block of the fundraiser (has to be after _fundingStartBlock).
* _roundTwoBlock The block that changes the discount rate to 20% (has to be between _fundingStartBlock and _roundThreeBlock).
* _roundThreeBlock The block that changes the discount rate to 10% (has to be between _roundTwoBlock and _roundFourBlock).
* _roundFourBlock The block that changes the discount rate to 0% (has to be between _roundThreeBlock and _fundingEndBlock).
* _admin1 The first admin account that owns this contract.
* _admin2 The second admin account that owns this contract.
* _tokenVendor The account that creates tokens for credit card / fiat contributers.
*/
function EVNToken(
uint256 _fundingStartBlock,
uint256 _fundingEndBlock,
uint256 _roundTwoBlock, // block number that triggers the first exchange rate change
uint256 _roundThreeBlock, // block number that triggers the second exchange rate change
uint256 _roundFourBlock,
address _admin1,
address _admin2,
address _tokenVendor,
uint256 _ccReleaseBlock)
payable
{
// Check that the parameters make sense
// The start of the fundraising should happen in the future
require (block.number <= _fundingStartBlock);
// The discount rate changes and ending should follow in their subsequent order
require (_fundingStartBlock < _roundTwoBlock);
require (_roundTwoBlock < _roundThreeBlock);
require (_roundThreeBlock < _roundFourBlock);
require (_roundFourBlock < _fundingEndBlock);
// block when tokens bought with CC will be released must be in the future
require (_fundingEndBlock < _ccReleaseBlock);
// admin1 and admin2 address must be set and must be different
require (_admin1 != 0x0);
require (_admin2 != 0x0);
require (_admin1 != _admin2);
// tokenVendor must be set and be different from admin1 and admin2
require (_tokenVendor != 0x0);
require (_tokenVendor != _admin1);
require (_tokenVendor != _admin2);
// provide some ETH for oraclize price feed
require (msg.value > 0);
// Init contract state
state = ContractState.Fundraising;
savedState = ContractState.Fundraising;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
roundTwoBlock = _roundTwoBlock;
roundThreeBlock = _roundThreeBlock;
roundFourBlock = _roundFourBlock;
ccReleaseBlock = _ccReleaseBlock;
totalSupply = 0;
admin1 = _admin1;
admin2 = _admin2;
tokenVendor = _tokenVendor;
//oraclize
oraclize_setCustomGasPrice(100000000000 wei); // set the gas price a little bit higher, so the pricefeed definitely works
updatePrice();
oraclizeQueryCost = oraclize_getPrice("URL");
}
//// oraclize START
// @dev oraclize is called recursively here - once a callback fetches the newest ETH price, the next callback is scheduled for the next hour again
function __callback(bytes32 myid, string result) {
require(msg.sender == oraclize_cbAddress());
// setting the token price here
ETH_USD_EXCHANGE_RATE_IN_CENTS = SafeMath.parse(result);
updatedPrice(result);
// fetch the next price
updatePrice();
}
function updatePrice() payable { // can be left public as a way for replenishing contract's ETH balance, just in case
if (msg.sender != oraclize_cbAddress()) {
require(msg.value >= 200 finney);
}
if (oraclize_getPrice("URL") > this.balance) {
newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee");
} else {
newOraclizeQuery("Oraclize sent, wait..");
// Schedule query in 1 hour. Set the gas amount to 220000, as parsing in __callback takes around 70000 - we play it safe.
oraclize_query(3600, "URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD", 220000);
}
}
//// oraclize END
// Overridden method to check for end of fundraising before allowing transfer of tokens
function transfer(address _to, uint256 _value)
public
isFinalized // Only allow token transfer after the fundraising has ended
isKycVerified(msg.sender)
hasEnoughUnlockedTokens(msg.sender, _value)
onlyPayloadSize(2)
returns (bool success)
{
bool result = super.transfer(_to, _value);
if (result) {
trackHolder(_to); // track the owner for later payouts
}
return result;
}
// Overridden method to check for end of fundraising before allowing transfer of tokens
function transferFrom(address _from, address _to, uint256 _value)
public
isFinalized // Only allow token transfer after the fundraising has ended
isKycVerified(msg.sender)
hasEnoughUnlockedTokens(msg.sender, _value)
onlyPayloadSize(3)
returns (bool success)
{
bool result = super.transferFrom(_from, _to, _value);
if (result) {
trackHolder(_to); // track the owner for later payouts
}
return result;
}
// Allow for easier balance checking
function getBalanceOf(address _owner)
constant
returns (uint256 _balance)
{
return balances[_owner];
}
// getting purchase details by ID - workaround, mappings with dynamically sized keys can't be made public yet.
function getPurchaseById(string _id)
constant
returns (address _buyer, uint256 _tokenAmount, bool _active){
_buyer = purchases[_id].buyer;
_tokenAmount = purchases[_id].tokenAmount;
_active = purchases[_id].active;
}
// Allows to figure out the amount of known token holders
function getHolderCount()
public
constant
returns (uint256 _holderCount)
{
return holders.length;
}
// Allows to figure out the amount of purchases
function getPurchaseCount()
public
constant
returns (uint256 _purchaseCount)
{
return purchaseArray.length;
}
// Allows for easier retrieval of holder by array index
function getHolder(uint256 _index)
public
constant
returns (address _holder)
{
return holders[_index];
}
function trackHolder(address _to)
private
returns (bool success)
{
// Check if the recipient is a known token holder
if (isHolder[_to] == false) {
// if not, add him to the holders array and mark him as a known holder
holders.push(_to);
isHolder[_to] = true;
}
return true;
}
/// @dev Accepts ether and creates new EVN tokens
function createTokens()
payable
external
isFundraising
{
require(block.number >= fundingStartBlock);
require(block.number <= fundingEndBlock);
require(msg.value > 0);
// First we check the ETH cap: would adding this amount to the total unKYCed eth and the already KYCed eth exceed the eth cap?
// return the contribution if the cap has been reached already
uint256 totalKycedAndUnKycEdEth = SafeMath.add(allUnKycedEth, allReceivedEth);
uint256 checkedReceivedEth = SafeMath.add(totalKycedAndUnKycEdEth, msg.value);
require(checkedReceivedEth <= ETH_RECEIVED_CAP);
// If all is fine with the ETH cap, we continue to check the
// minimum amount of tokens and the cap for how many tokens
// have been generated so far
// calculate the token amount
uint256 tokens = SafeMath.mul(msg.value, ETH_USD_EXCHANGE_RATE_IN_CENTS);
// divide by 100 to turn ETH_USD_EXCHANGE_RATE_IN_CENTS into full USD
tokens = tokens / 100;
// apply discount multiplier
tokens = safeMulPercentage(tokens, getCurrentDiscountRate());
require(tokens >= TOKEN_MIN);
uint256 checkedSupply = SafeMath.add(totalSupply, tokens);
require(checkedSupply <= TOKEN_CREATION_CAP);
// Only when all the checks have passed, then we check if the address is already KYCEd and then
// update the state (noKycEthBalances, allReceivedEth, totalSupply, and balances) of the contract
if (kycVerified[msg.sender] == false) {
// @dev The unKYCed eth balances are moved to ethBalances in unlockKyc()
noKycEthBalances[msg.sender] = SafeMath.add(noKycEthBalances[msg.sender], msg.value);
// add the contributed eth to the total unKYCed eth amount
allUnKycedEth = SafeMath.add(allUnKycedEth, msg.value);
} else {
// if buyer is already KYC unlocked...
ethBalances[msg.sender] = SafeMath.add(ethBalances[msg.sender], msg.value);
allReceivedEth = SafeMath.add(allReceivedEth, msg.value);
}
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
trackHolder(msg.sender);
// to force the check for KYC Status upon the user when he tries transferring tokens
// and exclude every later token owner
isIcoBuyer[msg.sender] = true;
// Log the creation of these tokens
LogCreateEVN(msg.sender, tokens);
}
//add a user to the KYC team
function addToKycTeam(address _teamMember)
onlyOwner
onlyPayloadSize(1){
isKycTeam[_teamMember] = true;
}
//remove a user from the KYC team
function removeFromKycTeam(address _teamMember)
onlyOwner
onlyPayloadSize(1){
isKycTeam[_teamMember] = false;
}
//called by KYC team
function unlockKyc(address _owner)
external
onlyKycTeam {
require(kycVerified[_owner] == false);
//unlock the owner to allow transfer of tokens
kycVerified[_owner] = true;
// we leave the ccLockedUpBalances[_owner] as is, because also KYCed users could cancel their CC payments
if (noKycEthBalances[_owner] > 0) { // check if the user was an ETH buyer
// now move the unKYCed eth balance to the regular ethBalance.
ethBalances[_owner] = noKycEthBalances[_owner];
// add the now KYCed eth to the total received eth
allReceivedEth = SafeMath.add(allReceivedEth, noKycEthBalances[_owner]);
// subtract the now KYCed eth from total amount of unKYCed eth
allUnKycedEth = SafeMath.sub(allUnKycedEth, noKycEthBalances[_owner]);
// and set the user's unKYCed eth balance to 0
noKycEthBalances[_owner] = 0; // preventing replay attacks
}
}
// Refusing KYC of a user, who only contributed in ETH.
// We must pay close attention here for the case that a user contributes in ETH AND(!) CC !
// in this case, he must only kill the tokens he received through ETH, the ones bought in fiat will be
// killed by canceling his payments and subsequently calling cancelDelivery() with the according payment id.
function refuseKyc(address _user)
external
onlyKycTeam
{
// once a user is verified, you can't kick him out.
require (kycVerified[_user] == false);
// immediately stop, if a user has none or only CC contributions.
// we're managing kyc refusing of CC contributors off-chain
require(noKycEthBalances[_user]>0);
uint256 EVNVal = balances[_user];
require(EVNVal > 0);
uint256 ethVal = noKycEthBalances[_user]; // refund un-KYCd eth
require(ethVal > 0);
// Update the state only after all the checks have passed
allUnKycedEth = SafeMath.sub(allUnKycedEth, noKycEthBalances[_user]); // or if there was any unKYCed Eth, subtract it from the total unKYCed eth balance.
balances[_user] = ccLockedUpBalances[_user]; // assign user only the token amount he has bought through CC, if there are any.
noKycEthBalances[_user] = 0;
totalSupply = SafeMath.sub(totalSupply, EVNVal); // Extra safe
// Log this refund
LogKycRefused(_user, ethVal);
// Send the contributions only after we have updated all the balances
// If you're using a contract, make sure it works with .transfer() gas limits
_user.transfer(ethVal);
}
// Called in case a buyer cancels his CC payment.
// @param The payment ID from payment provider
function cancelDelivery(string _purchaseID)
external
onlyKycTeam{
// CC payments are only cancelable until ccReleaseBlock
require (block.number < ccReleaseBlock);
// check if the purchase to cancel is still active
require (purchases[_purchaseID].active == true);
// now withdraw the canceled purchase's token amount from the user's balance
balances[purchases[_purchaseID].buyer] = SafeMath.sub(balances[purchases[_purchaseID].buyer], purchases[_purchaseID].tokenAmount);
// and withdraw the canceled purchase's token amount from the lockedUp token balance
ccLockedUpBalances[purchases[_purchaseID].buyer] = SafeMath.sub(ccLockedUpBalances[purchases[_purchaseID].buyer], purchases[_purchaseID].tokenAmount);
// set the purchase's status to inactive
purchases[_purchaseID].active = false;
//correct th amount of tokens generated
totalSupply = SafeMath.sub(totalSupply, purchases[_purchaseID].tokenAmount);
LogCancelDelivery(purchases[_purchaseID].buyer, _purchaseID);
}
// @dev Deliver tokens sold for CC/fiat and BTC
// @dev param _tokens in Cents, e.g. 1 Token == 1$, passed as 100 cents
// @dev param _btcBuyer Boolean to determine if the delivered tokens need to be locked (not the case for BTC buyers, their payment is final)
// @dev discount multipliers are applied off-contract in this case
function deliverTokens(address _to, uint256 _tokens, string _purchaseId, bool _btcBuyer)
external
isFundraising
onlyVendor
{
require(_to != 0x0);
require(_tokens > 0);
require(bytes(_purchaseId).length>0);
require(block.number >= fundingStartBlock);
require(block.number <= fundingEndBlock + 168000); // allow delivery of tokens sold for fiat for 28 days after end of ICO for safety reasons
// calculate the total amount of tokens and cut out the extra two decimal units,
// because _tokens was in cents.
uint256 tokens = SafeMath.mul(_tokens, (10**(decimals) / 10**2));
// continue to check for how many tokens
// have been generated so far
uint256 checkedSupply = SafeMath.add(totalSupply, tokens);
require(checkedSupply <= TOKEN_CREATION_CAP);
// Only when all the checks have passed, then we update the state (totalSupply, and balances) of the contract
totalSupply = checkedSupply;
// prevent from adding a delivery multiple times
require(purchases[_purchaseId].buyer==0x0);
// Log this information in order to be able to cancel token deliveries (on CC refund) by the payment ID
purchases[_purchaseId] = Purchase({
buyer: _to,
tokenAmount: tokens,
active: true
});
purchaseArray.push(_purchaseId);
// if tokens were not paid with BTC (but credit card), they need to be locked up
if (_btcBuyer == false) {
ccLockedUpBalances[_to] = SafeMath.add(ccLockedUpBalances[_to], tokens); // update user's locked up token balance
}
balances[_to] = SafeMath.add(balances[_to], tokens); // safeAdd not needed; bad semantics to use here
trackHolder(_to); // log holder's address
// to force the check for KYC Status upon the user when he tries transferring tokens
// and exclude every later token owner
isIcoBuyer[_to] = true;
// Log the creation of these tokens
LogDeliverEVN(_to, tokens);
}
/// @dev Returns the current token price
function getCurrentDiscountRate()
private
constant
returns (uint256 currentDiscountRate)
{
// determine which discount to apply
if (block.number < roundTwoBlock) {
// first round
return TOKEN_FIRST_DISCOUNT_MULTIPLIER;
} else if (block.number < roundThreeBlock){
// second round
return TOKEN_SECOND_DISCOUNT_MULTIPLIER;
} else if (block.number < roundFourBlock) {
// third round
return TOKEN_THIRD_DISCOUNT_MULTIPLIER;
} else {
// fourth round, no discount
return 100000;
}
}
/// @dev Allows to transfer ether from the contract as soon as the minimum is reached
function retrieveEth(uint256 _value, address _safe)
external
minimumReached
onlyOwner
{
require(SafeMath.sub(this.balance, _value) >= allUnKycedEth); // make sure unKYCed eth cannot be withdrawn
// make sure a recipient was defined !
require (_safe != 0x0);
// send the eth to where admins agree upon
_safe.transfer(_value);
}
/// @dev Ends the fundraising period and sends the ETH to wherever the admins agree upon
function finalize(address _safe)
external
isFundraising
minimumReached
onlyOwner // Only the admins calling this method exactly the same way can finalize the sale.
{
// Only allow to finalize the contract before the ending block if we already reached any of the two caps
require(block.number > fundingEndBlock || totalSupply >= TOKEN_CREATED_MIN || allReceivedEth >= ETH_RECEIVED_MIN);
// make sure a recipient was defined !
require (_safe != 0x0);
// Move the contract to Finalized state
state = ContractState.Finalized;
savedState = ContractState.Finalized;
// Send the KYCed ETH to where admins agree upon.
_safe.transfer(allReceivedEth);
}
/// @dev Pauses the contract
function pause()
external
notPaused // Prevent the contract getting stuck in the Paused state
onlyOwner // Only both admins calling this method can pause the contract
{
// Move the contract to Paused state
savedState = state;
state = ContractState.Paused;
}
/// @dev Proceeds with the contract
function proceed()
external
isPaused
onlyOwner // Only both admins calling this method can proceed with the contract
{
// Move the contract to the previous state
state = savedState;
}
/// @dev Allows contributors to recover their ether in case the minimum funding goal is not reached
function refund()
external
{
// Allow refunds only a week after end of funding to give KYC-team time to verify contributors
// and thereby move un-KYC-ed ETH over into allReceivedEth as well as deliver the tokens paid with CC
require(block.number > (fundingEndBlock + 42000));
// No refunds if the minimum has been reached or minimum of 1 Million Tokens have been generated
require(allReceivedEth < ETH_RECEIVED_MIN || totalSupply < TOKEN_CREATED_MIN);
// to prevent CC buyers from accidentally calling refund and burning their tokens
require (ethBalances[msg.sender] > 0 || noKycEthBalances[msg.sender] > 0);
// Only refund if there are EVN tokens
uint256 EVNVal = balances[msg.sender];
require(EVNVal > 0);
// refunds either KYCed eth or un-KYCd eth
uint256 ethVal = SafeMath.add(ethBalances[msg.sender], noKycEthBalances[msg.sender]);
require(ethVal > 0);
allReceivedEth = SafeMath.sub(allReceivedEth, ethBalances[msg.sender]); // subtract only the KYCed ETH from allReceivedEth, because the latter is what admins will only be able to withdraw
allUnKycedEth = SafeMath.sub(allUnKycedEth, noKycEthBalances[msg.sender]); // or if there was any unKYCed Eth, subtract it from the total unKYCed eth balance.
// Update the state only after all the checks have passed.
// reset everything to zero, no replay attacks.
balances[msg.sender] = 0;
ethBalances[msg.sender] = 0;
noKycEthBalances[msg.sender] = 0;
totalSupply = SafeMath.sub(totalSupply, EVNVal); // Extra safe
// Log this refund
LogRefund(msg.sender, ethVal);
// Send the contributions only after we have updated all the balances
// If you're using a contract, make sure it works with .transfer() gas limits
msg.sender.transfer(ethVal);
}
// @dev Deliver tokens to be distributed to team members
function deliverTeamTokens(address _to)
external
isFinalized
onlyOwner
{
require(teamTokensDelivered == false);
require(_to != 0x0);
// allow delivery of tokens for the company and supporters without vesting, team tokens will be supplied like a CC purchase.
// company and supporters gets 7% of a whole final pie, meaning we have to add ~7,5% to the
// current totalSupply now, basically stretching it and taking 7% from the result, so the 93% that remain equals the amount of tokens created right now.
// e.g. (93 * x = 100, where x amounts to roughly about 1.07526 and 7 would be the team's part)
uint256 newTotalSupply = safeMulPercentage(totalSupply, 107526);
// give company and supporters their 7%
uint256 tokens = SafeMath.sub(newTotalSupply, totalSupply);
balances[_to] = tokens;
//update state
teamTokensDelivered = true;
totalSupply = newTotalSupply;
trackHolder(_to);
// Log the creation of these tokens
LogTeamTokensDelivered(_to, tokens);
}
function safeMulPercentage(uint256 value, uint256 percentage)
internal
constant
returns (uint256 resultValue)
{
require(percentage >= 100000);
require(percentage < 200000);
// Multiply with percentage
uint256 newValue = SafeMath.mul(value, percentage);
// Remove the 5 extra decimals
newValue = newValue / 10**5;
return newValue;
}
// customizing the gas price for oraclize calls during "ICO Rush hours"
function setOraclizeGas(uint256 _option)
external
onlyOwner
{
if (_option <= 30) {
oraclize_setCustomGasPrice(30000000000 wei);
} else if (_option <= 50) {
oraclize_setCustomGasPrice(50000000000 wei);
} else if (_option <= 70) {
oraclize_setCustomGasPrice(70000000000 wei);
} else if (_option <= 100) {
oraclize_setCustomGasPrice(100000000000 wei);
}
}
} | total amount of ETH we have no KYC for yet
| uint256 public allUnKycedEth; | 6,349,019 | [
1,
4963,
3844,
434,
512,
2455,
732,
1240,
1158,
1475,
61,
39,
364,
4671,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2254,
5034,
1071,
777,
984,
47,
93,
3263,
41,
451,
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
] |
./partial_match/1/0x608f7dF36409888D17Ad1fCf258e59880840742E/sources/FusFund.sol | solium-disable-line uppercase
| string public constant name = "FusFund"; | 4,464,847 | [
1,
18281,
5077,
17,
8394,
17,
1369,
18966,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
533,
1071,
5381,
508,
273,
315,
42,
407,
42,
1074,
14432,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xD99ea23f1E50d4c117371C31f0C990B1e1ece1d5/sources/run/media/bill/Rekoner-0/puul/puul-contracts-public/contracts/pool/StakingBase.sol | This class is meant to be used to stake a token into a farm. Currently, it only handles getting the rewards from a farm and is only used by PuulStakingPool. Will be enhanced in the future. | contract StakingBase is TokenBase {
using Address for address;
using SafeMath for uint256;
using SafeERC20 for IERC20;
IERC20 private _staking;
pragma solidity >=0.6.12;
constructor (string memory name, string memory symbol, address token, address fees, address helper) public TokenBase(name, symbol, fees, helper) {
require(token != address(0), 'token==0');
_staking = IERC20(token);
}
function _initialize() internal override returns(bool success) {
return true;
}
function deposit(uint256 amount) external nonReentrant {
uint256 bef = _staking.balanceOf(address(this));
_staking.safeTransferFrom(msg.sender, address(this), amount);
uint256 aft = _staking.balanceOf(address(this));
uint256 sent = aft.sub(bef, '!deposit');
_deposit(sent);
}
function _earn() internal override virtual {
}
function _unearn(uint256 amount) internal override virtual {
}
function _withdrawFees() override internal returns(uint256 amount) {
amount = EarnPool._withdrawFees();
_staking.safeTransfer(msg.sender, amount);
}
function _withdraw(uint256 amount) override internal returns(uint256 afterFee) {
afterFee = EarnPool._withdraw(amount);
_staking.safeTransfer(msg.sender, afterFee);
}
function _tokenInUse(address token) override virtual internal view returns(bool) {
return token == address(_staking) || TokenBase._tokenInUse(token);
}
function withdrawAll() nonReentrant external override {
_withdraw(balanceOf(msg.sender));
}
function withdraw(uint256 amount) nonReentrant external override {
require(amount <= balanceOf(msg.sender));
_withdraw(amount);
}
function withdrawFees() onlyWithdrawal nonReentrant override external {
_withdrawFees();
}
}
| 8,307,786 | [
1,
2503,
667,
353,
20348,
358,
506,
1399,
358,
384,
911,
279,
1147,
1368,
279,
284,
4610,
18,
15212,
16,
518,
1338,
7372,
8742,
326,
283,
6397,
628,
279,
284,
4610,
471,
353,
1338,
1399,
635,
453,
89,
332,
510,
6159,
2864,
18,
9980,
506,
29865,
316,
326,
3563,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
934,
6159,
2171,
353,
3155,
2171,
288,
203,
225,
1450,
5267,
364,
1758,
31,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
203,
225,
467,
654,
39,
3462,
3238,
389,
334,
6159,
31,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
26,
18,
2138,
31,
203,
225,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
1758,
1147,
16,
1758,
1656,
281,
16,
1758,
4222,
13,
1071,
3155,
2171,
12,
529,
16,
3273,
16,
1656,
281,
16,
4222,
13,
288,
203,
565,
2583,
12,
2316,
480,
1758,
12,
20,
3631,
296,
2316,
631,
20,
8284,
203,
565,
389,
334,
6159,
273,
467,
654,
39,
3462,
12,
2316,
1769,
203,
225,
289,
203,
203,
225,
445,
389,
11160,
1435,
2713,
3849,
1135,
12,
6430,
2216,
13,
288,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
225,
445,
443,
1724,
12,
11890,
5034,
3844,
13,
3903,
1661,
426,
8230,
970,
288,
203,
565,
2254,
5034,
506,
74,
273,
389,
334,
6159,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
389,
334,
6159,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
565,
2254,
5034,
279,
1222,
273,
389,
334,
6159,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
2254,
5034,
3271,
273,
279,
1222,
18,
1717,
12,
2196,
74,
16,
11817,
323,
1724,
8284,
203,
565,
389,
323,
1724,
12,
7569,
1769,
203,
225,
2
] |
pragma solidity ^0.5.8;
/// @title Library to check Merkle proofs.
/// @dev Only trees of height 256+1 or less are supported.
library MerkleProof256 {
/// @notice Verify a Merkle proof.
/// @param proof List of hashes. Leaf's neighbor is first.
/// @param directions Direction of sibling along Merkle branch as a bitmap. If bit is 1, sibling proof element
/// is on the left. If bit is 1, sibling is on the right. Leaf's sibling is LSB.
/// @param root Root of Merkle tree.
/// @param leaf Leaf of verify.
/// @return True is the proof is valid, false otherwise.
function verify(bytes32[] memory proof, uint256 directions, bytes32 root, bytes32 leaf) internal pure returns (bool) {
require(proof.length <= 256);
bytes32 computedHash = leaf;
uint256 len = proof.length - 1;
for (uint256 i = 0; i <= len; i++) {
bytes32 proofElement = proof[i];
bool isLeft = directions & (1 << (len - i)) == 1;
if (isLeft) {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
} else {
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
}
}
return computedHash == root;
}
} | @notice Verify a Merkle proof. @param proof List of hashes. Leaf's neighbor is first. @param directions Direction of sibling along Merkle branch as a bitmap. If bit is 1, sibling proof element is on the left. If bit is 1, sibling is on the right. Leaf's sibling is LSB. @param root Root of Merkle tree. @param leaf Leaf of verify. @return True is the proof is valid, false otherwise. | function verify(bytes32[] memory proof, uint256 directions, bytes32 root, bytes32 leaf) internal pure returns (bool) {
require(proof.length <= 256);
bytes32 computedHash = leaf;
uint256 len = proof.length - 1;
for (uint256 i = 0; i <= len; i++) {
bytes32 proofElement = proof[i];
bool isLeft = directions & (1 << (len - i)) == 1;
if (isLeft) {
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
}
}
return computedHash == root;
}
| 5,396,543 | [
1,
8097,
279,
31827,
14601,
18,
225,
14601,
987,
434,
9869,
18,
23383,
1807,
10553,
353,
1122,
18,
225,
18558,
15280,
434,
10841,
7563,
31827,
3803,
487,
279,
9389,
18,
971,
2831,
353,
404,
16,
10841,
14601,
930,
540,
353,
603,
326,
2002,
18,
971,
2831,
353,
404,
16,
10841,
353,
603,
326,
2145,
18,
23383,
1807,
10841,
353,
511,
14541,
18,
225,
1365,
7450,
434,
31827,
2151,
18,
225,
7839,
23383,
434,
3929,
18,
327,
1053,
353,
326,
14601,
353,
923,
16,
629,
3541,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
3929,
12,
3890,
1578,
8526,
3778,
14601,
16,
2254,
5034,
18558,
16,
1731,
1578,
1365,
16,
1731,
1578,
7839,
13,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
24207,
18,
2469,
1648,
8303,
1769,
203,
203,
3639,
1731,
1578,
8470,
2310,
273,
7839,
31,
203,
3639,
2254,
5034,
562,
273,
14601,
18,
2469,
300,
404,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
1648,
562,
31,
277,
27245,
288,
203,
5411,
1731,
1578,
14601,
1046,
273,
14601,
63,
77,
15533,
203,
5411,
1426,
353,
3910,
273,
18558,
473,
261,
21,
2296,
261,
1897,
300,
277,
3719,
422,
404,
31,
203,
203,
5411,
309,
261,
291,
3910,
13,
288,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
24207,
1046,
16,
8470,
2310,
10019,
203,
7734,
8470,
2310,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
20307,
2310,
16,
14601,
1046,
10019,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
8470,
2310,
422,
1365,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Lockable is Ownable {
uint256 public creationTime;
bool public tokenTransferLocker;
mapping(address => bool) lockaddress;
event Locked(address lockaddress);
event Unlocked(address lockaddress);
event TokenTransferLocker(bool _setto);
// if Token transfer
modifier isTokenTransfer {
// only contract holder can send token during locked period
if(msg.sender != owner) {
// if token transfer is not allow
require(!tokenTransferLocker);
if(lockaddress[msg.sender]){
revert();
}
}
_;
}
// This modifier check whether the contract should be in a locked
// or unlocked state, then acts and updates accordingly if
// necessary
modifier checkLock {
if (lockaddress[msg.sender]) {
revert();
}
_;
}
constructor() public {
creationTime = now;
owner = msg.sender;
}
function isTokenTransferLocked()
external
view
returns (bool)
{
return tokenTransferLocker;
}
function enableTokenTransfer()
external
onlyOwner
{
delete tokenTransferLocker;
emit TokenTransferLocker(false);
}
function disableTokenTransfer()
external
onlyOwner
{
tokenTransferLocker = true;
emit TokenTransferLocker(true);
}
}
contract ERC20 {
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 public totalSupply;
function balanceOf(address who) view external returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract CoolPandaToken is ERC20, Lockable {
using SafeMath for uint256;
uint256 public decimals = 18;
address public fundWallet = 0x071961b88F848D09C3d988E8814F38cbAE755C44;
uint256 public tokenPrice;
function balanceOf(address _addr) external view returns (uint256) {
return balances[_addr];
}
function allowance(address _from, address _spender) external view returns (uint256) {
return allowed[_from][_spender];
}
function transfer(address _to, uint256 _value)
isTokenTransfer
public
returns (bool success) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint _value)
isTokenTransfer
external
returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
isTokenTransfer
public
returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
isTokenTransfer
external
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
function setFundWallet(address _newAddr) external onlyOwner {
require(_newAddr != address(0));
fundWallet = _newAddr;
}
function transferEth() onlyOwner external {
fundWallet.transfer(address(this).balance);
}
function setTokenPrice(uint256 _newBuyPrice) external onlyOwner {
tokenPrice = _newBuyPrice;
}
}
interface tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external; }
contract PaoToken is CoolPandaToken {
using SafeMath for uint256;
string public name = "PAO Token";
string public symbol = "PAO";
uint fundRatio = 6;
uint256 public minBuyETH = 50;
JPYC public jpyc; //JPYC Address
uint256 public jypcBonus = 40000;
event JypcBonus(uint256 paoAmount, uint256 jpycAmount);
// constructor
constructor() public {
totalSupply = 10000000000 * 10 ** uint256(decimals);
tokenPrice = 50000;
balances[fundWallet] = totalSupply * fundRatio / 10;
balances[address(this)] = totalSupply.sub(balances[fundWallet]);
}
// @notice Buy tokens from contract by sending ether
function () payable public {
if(fundWallet != msg.sender){
require (msg.value >= (minBuyETH * 10 ** uint256(decimals))); // Check if minimum amount
uint256 amount = msg.value.mul(tokenPrice); // calculates the amount
_buyToken(msg.sender, amount); // makes the transfers
fundWallet.transfer(msg.value); // send ether to the fundWallet
}
}
function _buyToken(address _to, uint256 _value) isTokenTransfer internal {
address _from = address(this);
require (_to != 0x0); // Prevent transfer to 0x0 address.
require (balances[_from] >= _value); // Check if the sender has enough
require (balances[_to].add(_value) >= balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
//give bonus consume token
uint256 _jpycAmount = _getJYPCBonus();
jpyc.giveBonus(_to, _jpycAmount);
emit JypcBonus(_value,_jpycAmount);
}
function _getJYPCBonus() internal view returns (uint256 amount){
return msg.value.mul(jypcBonus);
}
function setMinBuyEth(uint256 _amount) external onlyOwner{
minBuyETH = _amount;
}
function setJypcBonus(uint256 _amount) external onlyOwner{
jypcBonus = _amount;
}
function transferToken() onlyOwner external {
address _from = address(this);
uint256 _total = balances[_from];
balances[_from] = balances[_from].sub(_total);
balances[fundWallet] = balances[fundWallet].add(_total);
}
function setJpycContactAddress(address _tokenAddress) external onlyOwner {
jpyc = JPYC(_tokenAddress);
}
}
contract JPYC is CoolPandaToken {
using SafeMath for uint256;
string public name = "Japan Yen Coin";
uint256 _initialSupply = 10000000000 * 10 ** uint256(decimals);
string public symbol = "JPYC";
address public paoContactAddress;
event Issue(uint256 amount);
// constructor
constructor() public {
tokenPrice = 47000; //JPY to ETH (rough number)
totalSupply = _initialSupply;
balances[fundWallet] = _initialSupply;
}
function () payable public {
uint amount = msg.value.mul(tokenPrice); // calculates the amount
_giveToken(msg.sender, amount); // makes the transfers
fundWallet.transfer(msg.value); // send ether to the public collection wallet
}
function _giveToken(address _to, uint256 _value) isTokenTransfer internal {
require (_to != 0x0); // Prevent transfer to 0x0 address.
require(totalSupply.add(_value) >= totalSupply);
require (balances[_to].add(_value) >= balances[_to]); // Check for overflows
totalSupply = totalSupply.add(_value);
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
emit Transfer(address(this), _to, _value);
}
function issue(uint256 amount) external onlyOwner {
_giveToken(fundWallet, amount);
emit Issue(amount);
}
function setPaoContactAddress(address _newAddr) external onlyOwner {
require(_newAddr != address(0));
paoContactAddress = _newAddr;
}
function giveBonus(address _to, uint256 _value)
isTokenTransfer
external
returns (bool success) {
require(_to != address(0));
if(msg.sender == paoContactAddress){
_giveToken(_to,_value);
return true;
}
return false;
}
} | Add the same to the recipient
| balances[_to] = balances[_to].add(_value); | 6,701,385 | [
1,
986,
326,
1967,
358,
326,
8027,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
10402,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xe6420EEebdB7129b580c66051C2b1711bD9B83Ea/sources/ololo.sol | * @dev Auctionn NFT must have FOUNDER_ROLE and be owner of the nft./ | function sendTokenToAuction(address _to, uint256 _tokenId, uint256 _price, uint _auctionOpen, uint _biddingTime, uint _auctionExtendTime) public {
ERC721Upgradeable.safeTransferFrom(
msg.sender,
_to,
_tokenId,
abi.encodePacked(
uint256(_price),
uint(_auctionOpen),
uint(_biddingTime),
uint(_auctionExtendTime)
)
);
}
| 12,515,677 | [
1,
37,
4062,
82,
423,
4464,
1297,
1240,
17634,
31625,
67,
16256,
471,
506,
3410,
434,
326,
290,
1222,
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
] | [
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,
1366,
1345,
774,
37,
4062,
12,
2867,
389,
869,
16,
2254,
5034,
389,
2316,
548,
16,
2254,
5034,
389,
8694,
16,
2254,
389,
69,
4062,
3678,
16,
2254,
389,
70,
1873,
310,
950,
16,
2254,
389,
69,
4062,
16675,
950,
13,
1071,
288,
203,
3639,
4232,
39,
27,
5340,
10784,
429,
18,
4626,
5912,
1265,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
389,
869,
16,
203,
5411,
389,
2316,
548,
16,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
2254,
5034,
24899,
8694,
3631,
203,
7734,
2254,
24899,
69,
4062,
3678,
3631,
203,
7734,
2254,
24899,
70,
1873,
310,
950,
3631,
203,
7734,
2254,
24899,
69,
4062,
16675,
950,
13,
203,
5411,
262,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract ExampleContract {
// some state variables ...
event ReturnValue(address indexed _from, int256 _value);
function foo(int256 _value) returns (int256) {
// manipulate state ...
ReturnValue(msg.sender, _value);
return _value;
}
}
// contract ExampleContract {
// // some state variables ...
// function foo(int256 _value) returns (int256) {
// // manipulate state ...
// return _value;
// }
// } | manipulate state ... | function foo(int256 _value) returns (int256) {
ReturnValue(msg.sender, _value);
return _value;
}
| 12,980,083 | [
1,
4728,
625,
6243,
919,
1372,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
8431,
12,
474,
5034,
389,
1132,
13,
1135,
261,
474,
5034,
13,
288,
203,
377,
203,
565,
2000,
620,
12,
3576,
18,
15330,
16,
389,
1132,
1769,
203,
565,
327,
389,
1132,
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,
-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/0xd0699fe7FE1c3BFbE4F0347317B29284008FC8b7/sources/SUPERBONK.sol | * @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(0x3C4Ab1C5a5c46b8f11aF1903ad8DDafD8C99992A), "ERC20: transfer from the zero address");
require(recipient != address(0x3C4Ab1C5a5c46b8f11aF1903ad8DDafD8C99992A), "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);
}
| 9,246,585 | [
1,
19297,
1375,
8949,
68,
434,
2430,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
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,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
92,
23,
39,
24,
5895,
21,
39,
25,
69,
25,
71,
8749,
70,
28,
74,
2499,
69,
42,
3657,
4630,
361,
28,
5698,
1727,
40,
28,
39,
7991,
22,
37,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
92,
23,
39,
24,
5895,
21,
39,
25,
69,
25,
71,
8749,
70,
28,
74,
2499,
69,
42,
3657,
4630,
361,
28,
5698,
1727,
40,
28,
39,
7991,
22,
37,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
389,
5771,
1345,
5912,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
2254,
5034,
5793,
13937,
273,
389,
70,
26488,
63,
15330,
15533,
203,
3639,
2583,
12,
15330,
13937,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
11013,
8863,
203,
3639,
22893,
288,
203,
5411,
389,
70,
26488,
63,
15330,
65,
273,
5793,
13937,
300,
3844,
31,
203,
3639,
289,
203,
3639,
389,
70,
26488,
63,
20367,
65,
1011,
3844,
31,
203,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
203,
3639,
389,
5205,
1345,
5912,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, 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:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, 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 Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeCast.sol)
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";
/**
* @dev Flash-loan recipient interface
*/
interface IFlashLoanRecipient {
/**
* @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
*/
function onFlashLoan(
address caller,
IERC20 erc20Token,
uint256 amount,
uint256 feeAmount,
bytes memory data
) external;
}
/**
* @dev Bancor Network interface
*/
interface IBancorNetwork is IUpgradeable {
/**
* @dev returns the set of all valid pool collections
*/
function poolCollections() external view returns (IPoolCollection[] memory);
/**
* @dev returns the most recent collection that was added to the pool collections set for a specific type
*/
function latestPoolCollection(uint16 poolType) external view returns (IPoolCollection);
/**
* @dev returns the set of all liquidity pools
*/
function liquidityPools() external view returns (Token[] memory);
/**
* @dev returns the respective pool collection for the provided pool
*/
function collectionByPool(Token pool) external view returns (IPoolCollection);
/**
* @dev returns whether the pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev creates a new pool
*
* requirements:
*
* - the pool doesn't already exist
*/
function createPool(uint16 poolType, Token token) external;
/**
* @dev creates new pools
*
* requirements:
*
* - none of the pools already exists
*/
function createPools(uint16 poolType, Token[] calldata tokens) external;
/**
* @dev migrates a list of pools between pool collections
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*/
function migratePools(Token[] calldata pools) external;
/**
* @dev deposits liquidity for the specified provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function depositFor(
address provider,
Token pool,
uint256 tokenAmount
) external payable returns (uint256);
/**
* @dev deposits liquidity for the current provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must have approved the network to transfer the tokens on its behalf (except for in the
* native token case)
*/
function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);
/**
* @dev deposits liquidity for the specified provider by providing an EIP712 typed signature for an EIP2612 permit
* request and returns the respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositForPermitted(
address provider,
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev deposits liquidity by providing an EIP712 typed signature for an EIP2612 permit request and returns the
* respective pool token amount
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function depositPermitted(
Token pool,
uint256 tokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev initiates liquidity withdrawal
*
* requirements:
*
* - the caller must have approved the contract to transfer the pool token amount on its behalf
*/
function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);
/**
* @dev initiates liquidity withdrawal by providing an EIP712 typed signature for an EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function initWithdrawalPermitted(
IPoolToken poolToken,
uint256 poolTokenAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256);
/**
* @dev cancels a withdrawal request
*
* requirements:
*
* - the caller must have already initiated a withdrawal and received the specified id
*/
function cancelWithdrawal(uint256 id) external;
/**
* @dev withdraws liquidity and returns the withdrawn amount
*
* requirements:
*
* - the provider must have already initiated a withdrawal and received the specified id
* - the specified withdrawal request is eligible for completion
* - the provider must have approved the network to transfer VBNT amount on its behalf, when withdrawing BNT
* liquidity
*/
function withdraw(uint256 id) external returns (uint256);
/**
* @dev performs a trade by providing the input source amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the input source amount and providing an EIP712 typed signature for an
* EIP2612 permit request
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeBySourceAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev performs a trade by providing the output target amount
*
* requirements:
*
* - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
* native token case)
*/
function tradeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary
) external payable;
/**
* @dev performs a trade by providing the output target amount and providing an EIP712 typed signature for an
* EIP2612 permit request and returns the target amount and fee
*
* requirements:
*
* - the caller must have provided a valid and unused EIP712 typed signature
*/
function tradeByTargetAmountPermitted(
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount,
uint256 deadline,
address beneficiary,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev provides a flash-loan
*
* requirements:
*
* - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
*/
function flashLoan(
Token token,
uint256 amount,
IFlashLoanRecipient recipient,
bytes calldata data
) external;
/**
* @dev deposits liquidity during a migration
*/
function migrateLiquidity(
Token token,
address provider,
uint256 amount,
uint256 availableAmount,
uint256 originalAmount
) external payable;
/**
* @dev withdraws pending network fees
*
* requirements:
*
* - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
*/
function withdrawNetworkFees(address recipient) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
error NotWhitelisted();
struct VortexRewards {
// the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
uint32 burnRewardPPM;
// the maximum burn reward to be sent to the initiator of the burning event
uint256 burnRewardMaxAmount;
}
/**
* @dev Network Settings interface
*/
interface INetworkSettings is IUpgradeable {
/**
* @dev returns the protected tokens whitelist
*/
function protectedTokenWhitelist() external view returns (Token[] memory);
/**
* @dev checks whether a given token is whitelisted
*/
function isTokenWhitelisted(Token pool) external view returns (bool);
/**
* @dev returns the BNT funding limit for a given pool
*/
function poolFundingLimit(Token pool) external view returns (uint256);
/**
* @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
*/
function minLiquidityForTrading() external view returns (uint256);
/**
* @dev returns the global network fee (in units of PPM)
*
* notes:
*
* - the network fee is a portion of the total fees from each pool
*/
function networkFeePPM() external view returns (uint32);
/**
* @dev returns the withdrawal fee (in units of PPM)
*/
function withdrawalFeePPM() external view returns (uint32);
/**
* @dev returns the default flash-loan fee (in units of PPM)
*/
function defaultFlashLoanFeePPM() external view returns (uint32);
/**
* @dev returns the flash-loan fee (in units of PPM) of a pool
*/
function flashLoanFeePPM(Token pool) external view returns (uint32);
/**
* @dev returns the vortex settings
*/
function vortexRewards() external view returns (VortexRewards memory);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary } from "../token/TokenLibrary.sol";
import { IMasterVault } from "../vaults/interfaces/IMasterVault.sol";
import { IExternalProtectionVault } from "../vaults/interfaces/IExternalProtectionVault.sol";
import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { PPM_RESOLUTION } from "../utility/Constants.sol";
import { Owned } from "../utility/Owned.sol";
import { BlockNumber } from "../utility/BlockNumber.sol";
import { Fraction, Fraction112, FractionLibrary, zeroFraction, zeroFraction112 } from "../utility/FractionLibrary.sol";
import { Sint256, MathEx } from "../utility/MathEx.sol";
// prettier-ignore
import {
Utils,
AlreadyExists,
DoesNotExist,
InvalidPoolCollection,
InvalidStakedBalance
} from "../utility/Utils.sol";
import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol";
import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol";
import { IPoolToken } from "./interfaces/IPoolToken.sol";
import { IPoolTokenFactory } from "./interfaces/IPoolTokenFactory.sol";
import { IPoolMigrator } from "./interfaces/IPoolMigrator.sol";
// prettier-ignore
import {
AverageRate,
IPoolCollection,
PoolLiquidity,
Pool,
TRADING_STATUS_UPDATE_DEFAULT,
TRADING_STATUS_UPDATE_ADMIN,
TRADING_STATUS_UPDATE_MIN_LIQUIDITY,
TradeAmountAndFee,
WithdrawalAmounts
} from "./interfaces/IPoolCollection.sol";
import { IBNTPool } from "./interfaces/IBNTPool.sol";
import { PoolCollectionWithdrawal } from "./PoolCollectionWithdrawal.sol";
// base token withdrawal output amounts
struct InternalWithdrawalAmounts {
uint256 baseTokensToTransferFromMasterVault; // base token amount to transfer from the master vault to the provider
uint256 bntToMintForProvider; // BNT amount to mint directly for the provider
uint256 baseTokensToTransferFromEPV; // base token amount to transfer from the external protection vault to the provider
Sint256 baseTokensTradingLiquidityDelta; // base token amount to add to the trading liquidity
Sint256 bntTradingLiquidityDelta; // BNT amount to add to the trading liquidity and to the master vault
Sint256 bntProtocolHoldingsDelta; // BNT amount add to the protocol equity
uint256 baseTokensWithdrawalFee; // base token amount to keep in the pool as a withdrawal fee
uint256 baseTokensWithdrawalAmount; // base token amount equivalent to the base pool token's withdrawal amount
uint256 poolTokenTotalSupply; // base pool token's total supply
uint256 newBaseTokenTradingLiquidity; // new base token trading liquidity
uint256 newBNTTradingLiquidity; // new BNT trading liquidity
}
struct TradingLiquidityAction {
bool update;
uint256 newAmount;
}
enum PoolRateState {
Uninitialized,
Unstable,
Stable
}
/**
* @dev Pool Collection contract
*
* notes:
*
* - the address of reserve token serves as the pool unique ID in both contract functions and events
*/
contract PoolCollection is IPoolCollection, Owned, BlockNumber, Utils {
using TokenLibrary for Token;
using FractionLibrary for Fraction;
using FractionLibrary for Fraction112;
using EnumerableSet for EnumerableSet.AddressSet;
error AlreadyEnabled();
error DepositLimitExceeded();
error DepositingDisabled();
error InsufficientLiquidity();
error InsufficientSourceAmount();
error InsufficientTargetAmount();
error InvalidRate();
error RateUnstable();
error TradingDisabled();
uint16 private constant POOL_TYPE = 1;
uint256 private constant LIQUIDITY_GROWTH_FACTOR = 2;
uint256 private constant BOOTSTRAPPING_LIQUIDITY_BUFFER_FACTOR = 2;
uint32 private constant DEFAULT_TRADING_FEE_PPM = 2000; // 0.2%
uint32 private constant RATE_MAX_DEVIATION_PPM = 10000; // %1
// the average rate is recalculated based on the ratio between the weights of the rates the smaller the weights are,
// the larger the supported range of each one of the rates is
uint256 private constant EMA_AVERAGE_RATE_WEIGHT = 4;
uint256 private constant EMA_SPOT_RATE_WEIGHT = 1;
struct TradeIntermediateResult {
uint256 sourceAmount;
uint256 targetAmount;
uint256 limit;
uint256 tradingFeeAmount;
uint256 networkFeeAmount;
uint256 sourceBalance;
uint256 targetBalance;
uint256 stakedBalance;
Token pool;
bool isSourceBNT;
bool bySourceAmount;
uint32 tradingFeePPM;
bytes32 contextId;
}
struct TradeAmountAndTradingFee {
uint256 amount;
uint256 tradingFeeAmount;
}
// the network contract
IBancorNetwork private immutable _network;
// the address of the BNT token
IERC20 private immutable _bnt;
// the network settings contract
INetworkSettings private immutable _networkSettings;
// the master vault contract
IMasterVault private immutable _masterVault;
// the BNT pool contract
IBNTPool internal immutable _bntPool;
// the address of the external protection vault
IExternalProtectionVault private immutable _externalProtectionVault;
// the pool token factory contract
IPoolTokenFactory private immutable _poolTokenFactory;
// the pool migrator contract
IPoolMigrator private immutable _poolMigrator;
// a mapping between tokens and their pools
mapping(Token => Pool) internal _poolData;
// the set of all pools which are managed by this pool collection
EnumerableSet.AddressSet private _pools;
// the default trading fee (in units of PPM)
uint32 private _defaultTradingFeePPM;
/**
* @dev triggered when a pool is created
*/
event PoolCreated(IPoolToken indexed poolToken, Token indexed token);
/**
* @dev triggered when the default trading fee is updated
*/
event DefaultTradingFeePPMUpdated(uint32 prevFeePPM, uint32 newFeePPM);
/**
* @dev triggered when a specific pool's trading fee is updated
*/
event TradingFeePPMUpdated(Token indexed pool, uint32 prevFeePPM, uint32 newFeePPM);
/**
* @dev triggered when trading in a specific pool is enabled/disabled
*/
event TradingEnabled(Token indexed pool, bool indexed newStatus, uint8 indexed reason);
/**
* @dev triggered when depositing into a specific pool is enabled/disabled
*/
event DepositingEnabled(Token indexed pool, bool indexed newStatus);
/**
* @dev triggered when a pool's deposit limit is updated
*/
event DepositLimitUpdated(Token indexed pool, uint256 prevDepositLimit, uint256 newDepositLimit);
/**
* @dev triggered when new liquidity is deposited into a pool
*/
event TokensDeposited(
bytes32 indexed contextId,
address indexed provider,
Token indexed token,
uint256 tokenAmount,
uint256 poolTokenAmount
);
/**
* @dev triggered when existing liquidity is withdrawn from a pool
*/
event TokensWithdrawn(
bytes32 indexed contextId,
address indexed provider,
Token indexed token,
uint256 tokenAmount,
uint256 poolTokenAmount,
uint256 externalProtectionBaseTokenAmount,
uint256 bntAmount,
uint256 withdrawalFeeAmount
);
/**
* @dev triggered when the trading liquidity in a pool is updated
*/
event TradingLiquidityUpdated(
bytes32 indexed contextId,
Token indexed pool,
Token indexed token,
uint256 prevLiquidity,
uint256 newLiquidity
);
/**
* @dev triggered when the total liquidity in a pool is updated
*/
event TotalLiquidityUpdated(
bytes32 indexed contextId,
Token indexed pool,
uint256 liquidity,
uint256 stakedBalance,
uint256 poolTokenSupply
);
/**
* @dev initializes a new PoolCollection contract
*/
constructor(
IBancorNetwork initNetwork,
IERC20 initBNT,
INetworkSettings initNetworkSettings,
IMasterVault initMasterVault,
IBNTPool initBNTPool,
IExternalProtectionVault initExternalProtectionVault,
IPoolTokenFactory initPoolTokenFactory,
IPoolMigrator initPoolMigrator
)
validAddress(address(initNetwork))
validAddress(address(initBNT))
validAddress(address(initNetworkSettings))
validAddress(address(initMasterVault))
validAddress(address(initBNTPool))
validAddress(address(initExternalProtectionVault))
validAddress(address(initPoolTokenFactory))
validAddress(address(initPoolMigrator))
{
_network = initNetwork;
_bnt = initBNT;
_networkSettings = initNetworkSettings;
_masterVault = initMasterVault;
_bntPool = initBNTPool;
_externalProtectionVault = initExternalProtectionVault;
_poolTokenFactory = initPoolTokenFactory;
_poolMigrator = initPoolMigrator;
_setDefaultTradingFeePPM(DEFAULT_TRADING_FEE_PPM);
}
/**
* @inheritdoc IVersioned
*/
function version() external view virtual returns (uint16) {
return 2;
}
/**
* @inheritdoc IPoolCollection
*/
function poolType() external pure returns (uint16) {
return POOL_TYPE;
}
/**
* @inheritdoc IPoolCollection
*/
function defaultTradingFeePPM() external view returns (uint32) {
return _defaultTradingFeePPM;
}
/**
* @inheritdoc IPoolCollection
*/
function pools() external view returns (Token[] memory) {
uint256 length = _pools.length();
Token[] memory list = new Token[](length);
for (uint256 i = 0; i < length; i++) {
list[i] = Token(_pools.at(i));
}
return list;
}
/**
* @inheritdoc IPoolCollection
*/
function poolCount() external view returns (uint256) {
return _pools.length();
}
/**
* @dev sets the default trading fee (in units of PPM)
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setDefaultTradingFeePPM(uint32 newDefaultTradingFeePPM)
external
onlyOwner
validFee(newDefaultTradingFeePPM)
{
_setDefaultTradingFeePPM(newDefaultTradingFeePPM);
}
/**
* @inheritdoc IPoolCollection
*/
function createPool(Token token) external only(address(_network)) {
if (!_networkSettings.isTokenWhitelisted(token)) {
revert NotWhitelisted();
}
IPoolToken newPoolToken = IPoolToken(_poolTokenFactory.createPoolToken(token));
newPoolToken.acceptOwnership();
Pool memory newPool = Pool({
poolToken: newPoolToken,
tradingFeePPM: _defaultTradingFeePPM,
tradingEnabled: false,
depositingEnabled: true,
averageRate: AverageRate({ blockNumber: 0, rate: zeroFraction112() }),
depositLimit: 0,
liquidity: PoolLiquidity({ bntTradingLiquidity: 0, baseTokenTradingLiquidity: 0, stakedBalance: 0 })
});
_addPool(token, newPool);
emit PoolCreated({ poolToken: newPoolToken, token: token });
emit TradingEnabled({ pool: token, newStatus: false, reason: TRADING_STATUS_UPDATE_DEFAULT });
emit TradingFeePPMUpdated({ pool: token, prevFeePPM: 0, newFeePPM: newPool.tradingFeePPM });
emit DepositingEnabled({ pool: token, newStatus: newPool.depositingEnabled });
emit DepositLimitUpdated({ pool: token, prevDepositLimit: 0, newDepositLimit: newPool.depositLimit });
}
/**
* @inheritdoc IPoolCollection
*/
function isPoolValid(Token pool) external view returns (bool) {
return address(_poolData[pool].poolToken) != address(0);
}
/**
* @inheritdoc IPoolCollection
*/
function poolData(Token pool) external view returns (Pool memory) {
return _poolData[pool];
}
/**
* @inheritdoc IPoolCollection
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory) {
return _poolData[pool].liquidity;
}
/**
* @inheritdoc IPoolCollection
*/
function poolToken(Token pool) external view returns (IPoolToken) {
return _poolData[pool].poolToken;
}
/**
* @inheritdoc IPoolCollection
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256) {
Pool storage data = _poolData[pool];
return _poolTokenToUnderlying(poolTokenAmount, data.poolToken.totalSupply(), data.liquidity.stakedBalance);
}
/**
* @inheritdoc IPoolCollection
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256) {
Pool storage data = _poolData[pool];
return _underlyingToPoolToken(tokenAmount, data.poolToken.totalSupply(), data.liquidity.stakedBalance);
}
/**
* @inheritdoc IPoolCollection
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256) {
if (tokenAmountToDistribute == 0) {
return 0;
}
Pool storage data = _poolData[pool];
uint256 poolTokenSupply = data.poolToken.totalSupply();
uint256 val = tokenAmountToDistribute * poolTokenSupply;
return
MathEx.mulDivF(
val,
poolTokenSupply,
val + data.liquidity.stakedBalance * (poolTokenSupply - protocolPoolTokenAmount)
);
}
/**
* @dev sets the trading fee of a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setTradingFeePPM(Token pool, uint32 newTradingFeePPM) external onlyOwner validFee(newTradingFeePPM) {
Pool storage data = _poolStorage(pool);
uint32 prevTradingFeePPM = data.tradingFeePPM;
if (prevTradingFeePPM == newTradingFeePPM) {
return;
}
data.tradingFeePPM = newTradingFeePPM;
emit TradingFeePPMUpdated({ pool: pool, prevFeePPM: prevTradingFeePPM, newFeePPM: newTradingFeePPM });
}
/**
* @dev enables trading in a given pool, by providing the funding rate as two virtual balances, and updates its
* trading liquidity
*
* please note that the virtual balances should be derived from token prices, normalized to the smallest unit of
* tokens. For example:
*
* - if the price of one (10**18 wei) BNT is $X and the price of one (10**18 wei) TKN is $Y, then the virtual balances
* should represent a ratio of X to Y
* - if the price of one (10**18 wei) BNT is $X and the price of one (10**6 wei) USDC is $Y, then the virtual balances
* should represent a ratio of X to Y*10**12
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function enableTrading(
Token pool,
uint256 bntVirtualBalance,
uint256 baseTokenVirtualBalance
) external onlyOwner {
Fraction memory fundingRate = Fraction({ n: bntVirtualBalance, d: baseTokenVirtualBalance });
_validRate(fundingRate);
Pool storage data = _poolStorage(pool);
if (data.tradingEnabled) {
revert AlreadyEnabled();
}
// adjust the trading liquidity based on the base token vault balance and funding limits
uint256 minLiquidityForTrading = _networkSettings.minLiquidityForTrading();
_updateTradingLiquidity(bytes32(0), pool, data, data.liquidity, fundingRate, minLiquidityForTrading);
// verify that the BNT trading liquidity is equal or greater than the minimum liquidity for trading
if (data.liquidity.bntTradingLiquidity < minLiquidityForTrading) {
revert InsufficientLiquidity();
}
data.averageRate = AverageRate({ blockNumber: _blockNumber(), rate: fundingRate.toFraction112() });
data.tradingEnabled = true;
emit TradingEnabled({ pool: pool, newStatus: true, reason: TRADING_STATUS_UPDATE_ADMIN });
}
/**
* @dev disables trading in a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function disableTrading(Token pool) external onlyOwner {
Pool storage data = _poolStorage(pool);
_resetTradingLiquidity(bytes32(0), pool, data, TRADING_STATUS_UPDATE_ADMIN);
}
/**
* @dev enables/disables depositing into a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function enableDepositing(Token pool, bool status) external onlyOwner {
Pool storage data = _poolStorage(pool);
if (data.depositingEnabled == status) {
return;
}
data.depositingEnabled = status;
emit DepositingEnabled({ pool: pool, newStatus: status });
}
/**
* @dev sets the deposit limit of a given pool
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function setDepositLimit(Token pool, uint256 newDepositLimit) external onlyOwner {
Pool storage data = _poolStorage(pool);
uint256 prevDepositLimit = data.depositLimit;
if (prevDepositLimit == newDepositLimit) {
return;
}
data.depositLimit = newDepositLimit;
emit DepositLimitUpdated({ pool: pool, prevDepositLimit: prevDepositLimit, newDepositLimit: newDepositLimit });
}
/**
* @inheritdoc IPoolCollection
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external only(address(_network)) validAddress(provider) greaterThanZero(tokenAmount) returns (uint256) {
Pool storage data = _poolStorage(pool);
if (!data.depositingEnabled) {
revert DepositingDisabled();
}
// calculate the pool token amount to mint
uint256 currentStakedBalance = data.liquidity.stakedBalance;
uint256 prevPoolTokenTotalSupply = data.poolToken.totalSupply();
uint256 poolTokenAmount = _underlyingToPoolToken(tokenAmount, prevPoolTokenTotalSupply, currentStakedBalance);
// verify that the staked balance and the newly deposited amount isn't higher than the deposit limit
uint256 newStakedBalance = currentStakedBalance + tokenAmount;
if (newStakedBalance > data.depositLimit) {
revert DepositLimitExceeded();
}
PoolLiquidity memory prevLiquidity = data.liquidity;
// update the staked balance with the full base token amount
data.liquidity.stakedBalance = newStakedBalance;
// mint pool tokens to the provider
data.poolToken.mint(provider, poolTokenAmount);
// adjust the trading liquidity based on the base token vault balance and funding limits
_updateTradingLiquidity(
contextId,
pool,
data,
data.liquidity,
data.averageRate.rate.fromFraction112(),
_networkSettings.minLiquidityForTrading()
);
emit TokensDeposited({
contextId: contextId,
provider: provider,
token: pool,
tokenAmount: tokenAmount,
poolTokenAmount: poolTokenAmount
});
_dispatchTradingLiquidityEvents(
contextId,
pool,
prevPoolTokenTotalSupply + poolTokenAmount,
prevLiquidity,
data.liquidity
);
return poolTokenAmount;
}
/**
* @inheritdoc IPoolCollection
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external only(address(_network)) validAddress(provider) greaterThanZero(poolTokenAmount) returns (uint256) {
Pool storage data = _poolStorage(pool);
// obtain the withdrawal amounts
InternalWithdrawalAmounts memory amounts = _poolWithdrawalAmounts(pool, data, poolTokenAmount);
// execute the actual withdrawal
_executeWithdrawal(contextId, provider, pool, data, poolTokenAmount, amounts);
return amounts.baseTokensToTransferFromMasterVault;
}
/**
* @inheritdoc IPoolCollection
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount)
external
view
validAddress(address(pool))
greaterThanZero(poolTokenAmount)
returns (WithdrawalAmounts memory)
{
InternalWithdrawalAmounts memory amounts = _poolWithdrawalAmounts(pool, _poolStorage(pool), poolTokenAmount);
return
WithdrawalAmounts({
totalAmount: amounts.baseTokensWithdrawalAmount - amounts.baseTokensWithdrawalFee,
baseTokenAmount: amounts.baseTokensToTransferFromMasterVault + amounts.baseTokensToTransferFromEPV,
bntAmount: amounts.bntToMintForProvider
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
)
external
only(address(_network))
greaterThanZero(sourceAmount)
greaterThanZero(minReturnAmount)
returns (TradeAmountAndFee memory)
{
TradeIntermediateResult memory result = _initTrade(
contextId,
sourceToken,
targetToken,
sourceAmount,
minReturnAmount,
true
);
_performTrade(result);
return
TradeAmountAndFee({
amount: result.targetAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
)
external
only(address(_network))
greaterThanZero(targetAmount)
greaterThanZero(maxSourceAmount)
returns (TradeAmountAndFee memory)
{
TradeIntermediateResult memory result = _initTrade(
contextId,
sourceToken,
targetToken,
targetAmount,
maxSourceAmount,
false
);
_performTrade(result);
return
TradeAmountAndFee({
amount: result.sourceAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view greaterThanZero(sourceAmount) returns (TradeAmountAndFee memory) {
TradeIntermediateResult memory result = _initTrade(bytes32(0), sourceToken, targetToken, sourceAmount, 1, true);
_processTrade(result);
return
TradeAmountAndFee({
amount: result.targetAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view greaterThanZero(targetAmount) returns (TradeAmountAndFee memory) {
TradeIntermediateResult memory result = _initTrade(
bytes32(0),
sourceToken,
targetToken,
targetAmount,
type(uint256).max,
false
);
_processTrade(result);
return
TradeAmountAndFee({
amount: result.sourceAmount,
tradingFeeAmount: result.tradingFeeAmount,
networkFeeAmount: result.networkFeeAmount
});
}
/**
* @inheritdoc IPoolCollection
*/
function onFeesCollected(Token pool, uint256 feeAmount) external only(address(_network)) {
if (feeAmount == 0) {
return;
}
Pool storage data = _poolStorage(pool);
// increase the staked balance by the given amount
data.liquidity.stakedBalance += feeAmount;
}
/**
* @inheritdoc IPoolCollection
*/
function migratePoolIn(Token pool, Pool calldata data)
external
validAddress(address(pool))
only(address(_poolMigrator))
{
_addPool(pool, data);
data.poolToken.acceptOwnership();
}
/**
* @inheritdoc IPoolCollection
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection)
external
validAddress(address(targetPoolCollection))
only(address(_poolMigrator))
{
if (_network.latestPoolCollection(POOL_TYPE) != targetPoolCollection) {
revert InvalidPoolCollection();
}
IPoolToken cachedPoolToken = _poolData[pool].poolToken;
_removePool(pool);
cachedPoolToken.transferOwnership(address(targetPoolCollection));
}
/**
* @dev adds a pool
*/
function _addPool(Token pool, Pool memory data) private {
if (!_pools.add(address(pool))) {
revert AlreadyExists();
}
_poolData[pool] = data;
}
/**
* @dev removes a pool
*/
function _removePool(Token pool) private {
if (!_pools.remove(address(pool))) {
revert DoesNotExist();
}
delete _poolData[pool];
}
/**
* @dev returns withdrawal amounts
*/
function _poolWithdrawalAmounts(
Token pool,
Pool memory data,
uint256 poolTokenAmount
) internal view returns (InternalWithdrawalAmounts memory) {
// the base token trading liquidity of a given pool can never be higher than the base token balance of the vault
// whenever the base token trading liquidity is updated, it is set to at most the base token balance of the vault
uint256 baseTokenExcessAmount = pool.balanceOf(address(_masterVault)) -
data.liquidity.baseTokenTradingLiquidity;
uint256 poolTokenTotalSupply = data.poolToken.totalSupply();
uint256 baseTokensWithdrawalAmount = _poolTokenToUnderlying(
poolTokenAmount,
poolTokenTotalSupply,
data.liquidity.stakedBalance
);
PoolCollectionWithdrawal.Output memory output = PoolCollectionWithdrawal.calculateWithdrawalAmounts(
data.liquidity.bntTradingLiquidity,
data.liquidity.baseTokenTradingLiquidity,
baseTokenExcessAmount,
data.liquidity.stakedBalance,
pool.balanceOf(address(_externalProtectionVault)),
data.tradingFeePPM,
_networkSettings.withdrawalFeePPM(),
baseTokensWithdrawalAmount
);
return
InternalWithdrawalAmounts({
baseTokensToTransferFromMasterVault: output.s,
bntToMintForProvider: output.t,
baseTokensToTransferFromEPV: output.u,
baseTokensTradingLiquidityDelta: output.r,
bntTradingLiquidityDelta: output.p,
bntProtocolHoldingsDelta: output.q,
baseTokensWithdrawalFee: output.v,
baseTokensWithdrawalAmount: baseTokensWithdrawalAmount,
poolTokenTotalSupply: poolTokenTotalSupply,
newBaseTokenTradingLiquidity: output.r.isNeg
? data.liquidity.baseTokenTradingLiquidity - output.r.value
: data.liquidity.baseTokenTradingLiquidity + output.r.value,
newBNTTradingLiquidity: output.p.isNeg
? data.liquidity.bntTradingLiquidity - output.p.value
: data.liquidity.bntTradingLiquidity + output.p.value
});
}
/**
* @dev executes the following actions:
*
* - burn the network's base pool tokens
* - update the pool's base token staked balance
* - update the pool's base token trading liquidity
* - update the pool's BNT trading liquidity
* - update the pool's trading liquidity product
* - emit an event if the pool's BNT trading liquidity has crossed the minimum threshold
* (either above the threshold or below the threshold)
*/
function _executeWithdrawal(
bytes32 contextId,
address provider,
Token pool,
Pool storage data,
uint256 poolTokenAmount,
InternalWithdrawalAmounts memory amounts
) private {
PoolLiquidity storage liquidity = data.liquidity;
PoolLiquidity memory prevLiquidity = liquidity;
AverageRate memory averageRate = data.averageRate;
if (_poolRateState(prevLiquidity, averageRate) == PoolRateState.Unstable) {
revert RateUnstable();
}
data.poolToken.burnFrom(address(_network), poolTokenAmount);
uint256 newPoolTokenTotalSupply = amounts.poolTokenTotalSupply - poolTokenAmount;
liquidity.stakedBalance = MathEx.mulDivF(
liquidity.stakedBalance,
newPoolTokenTotalSupply,
amounts.poolTokenTotalSupply
);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
liquidity.baseTokenTradingLiquidity = SafeCast.toUint128(amounts.newBaseTokenTradingLiquidity);
liquidity.bntTradingLiquidity = SafeCast.toUint128(amounts.newBNTTradingLiquidity);
if (amounts.bntProtocolHoldingsDelta.value > 0) {
assert(amounts.bntProtocolHoldingsDelta.isNeg); // currently no support for requesting funding here
_bntPool.renounceFunding(contextId, pool, amounts.bntProtocolHoldingsDelta.value);
} else if (amounts.bntTradingLiquidityDelta.value > 0) {
if (amounts.bntTradingLiquidityDelta.isNeg) {
_bntPool.burnFromVault(amounts.bntTradingLiquidityDelta.value);
} else {
_bntPool.mint(address(_masterVault), amounts.bntTradingLiquidityDelta.value);
}
}
// if the provider should receive some BNT - ask the BNT pool to mint BNT to the provider
if (amounts.bntToMintForProvider > 0) {
_bntPool.mint(address(provider), amounts.bntToMintForProvider);
}
// if the provider should receive some base tokens from the external protection vault - remove the tokens from
// the external protection vault and send them to the master vault
if (amounts.baseTokensToTransferFromEPV > 0) {
_externalProtectionVault.withdrawFunds(
pool,
payable(address(_masterVault)),
amounts.baseTokensToTransferFromEPV
);
amounts.baseTokensToTransferFromMasterVault += amounts.baseTokensToTransferFromEPV;
}
// if the provider should receive some base tokens from the master vault - remove the tokens from the master
// vault and send them to the provider
if (amounts.baseTokensToTransferFromMasterVault > 0) {
_masterVault.withdrawFunds(pool, payable(provider), amounts.baseTokensToTransferFromMasterVault);
}
// ensure that the average rate is reset when the pool is being emptied
if (amounts.newBaseTokenTradingLiquidity == 0) {
data.averageRate.rate = zeroFraction112();
}
// if the new BNT trading liquidity is below the minimum liquidity for trading - reset the liquidity
if (amounts.newBNTTradingLiquidity < _networkSettings.minLiquidityForTrading()) {
_resetTradingLiquidity(
contextId,
pool,
data,
amounts.newBNTTradingLiquidity,
TRADING_STATUS_UPDATE_MIN_LIQUIDITY
);
}
emit TokensWithdrawn({
contextId: contextId,
provider: provider,
token: pool,
tokenAmount: amounts.baseTokensToTransferFromMasterVault,
poolTokenAmount: poolTokenAmount,
externalProtectionBaseTokenAmount: amounts.baseTokensToTransferFromEPV,
bntAmount: amounts.bntToMintForProvider,
withdrawalFeeAmount: amounts.baseTokensWithdrawalFee
});
_dispatchTradingLiquidityEvents(contextId, pool, newPoolTokenTotalSupply, prevLiquidity, data.liquidity);
}
/**
* @dev sets the default trading fee (in units of PPM)
*/
function _setDefaultTradingFeePPM(uint32 newDefaultTradingFeePPM) private {
uint32 prevDefaultTradingFeePPM = _defaultTradingFeePPM;
if (prevDefaultTradingFeePPM == newDefaultTradingFeePPM) {
return;
}
_defaultTradingFeePPM = newDefaultTradingFeePPM;
emit DefaultTradingFeePPMUpdated({ prevFeePPM: prevDefaultTradingFeePPM, newFeePPM: newDefaultTradingFeePPM });
}
/**
* @dev returns a storage reference to pool data
*/
function _poolStorage(Token pool) private view returns (Pool storage) {
Pool storage data = _poolData[pool];
if (address(data.poolToken) == address(0)) {
revert DoesNotExist();
}
return data;
}
/**
* @dev calculates base tokens amount
*/
function _poolTokenToUnderlying(
uint256 poolTokenAmount,
uint256 poolTokenSupply,
uint256 stakedBalance
) private pure returns (uint256) {
if (poolTokenSupply == 0) {
// if this is the initial liquidity provision - use a one-to-one pool token to base token rate
if (stakedBalance > 0) {
revert InvalidStakedBalance();
}
return poolTokenAmount;
}
return MathEx.mulDivF(poolTokenAmount, stakedBalance, poolTokenSupply);
}
/**
* @dev calculates pool tokens amount
*/
function _underlyingToPoolToken(
uint256 tokenAmount,
uint256 poolTokenSupply,
uint256 stakedBalance
) private pure returns (uint256) {
if (poolTokenSupply == 0) {
// if this is the initial liquidity provision - use a one-to-one pool token to base token rate
if (stakedBalance > 0) {
revert InvalidStakedBalance();
}
return tokenAmount;
}
return MathEx.mulDivC(tokenAmount, poolTokenSupply, stakedBalance);
}
/**
* @dev returns the target BNT trading liquidity, and whether or not it needs to be updated
*/
function _calcTargetBNTTradingLiquidity(
uint256 tokenReserveAmount,
uint256 availableFunding,
PoolLiquidity memory liquidity,
Fraction memory fundingRate,
uint256 minLiquidityForTrading
) private pure returns (TradingLiquidityAction memory) {
// calculate the target BNT trading liquidity based on the smaller between the following:
// - BNT liquidity required to match previously deposited based token liquidity
// - maximum available BNT trading liquidity (current amount + available funding)
uint256 targetBNTTradingLiquidity = Math.min(
MathEx.mulDivF(tokenReserveAmount, fundingRate.n, fundingRate.d),
liquidity.bntTradingLiquidity + availableFunding
);
// ensure that the target is above the minimum liquidity for trading
if (targetBNTTradingLiquidity < minLiquidityForTrading) {
return TradingLiquidityAction({ update: true, newAmount: 0 });
}
// calculate the new BNT trading liquidity and cap it by the growth factor
if (liquidity.bntTradingLiquidity == 0) {
// if the current BNT trading liquidity is 0, set it to the minimum liquidity for trading (with an
// additional buffer so that initial trades will be less likely to trigger disabling of trading)
uint256 newTargetBNTTradingLiquidity = minLiquidityForTrading * BOOTSTRAPPING_LIQUIDITY_BUFFER_FACTOR;
// ensure that we're not allocating more than the previously established limits
if (newTargetBNTTradingLiquidity > targetBNTTradingLiquidity) {
return TradingLiquidityAction({ update: false, newAmount: 0 });
}
targetBNTTradingLiquidity = newTargetBNTTradingLiquidity;
} else if (targetBNTTradingLiquidity >= liquidity.bntTradingLiquidity) {
// if the target is above the current trading liquidity, limit it by factoring the current value up. Please
// note that if the target is below the current trading liquidity - it will be reduced to it immediately
targetBNTTradingLiquidity = Math.min(
targetBNTTradingLiquidity,
liquidity.bntTradingLiquidity * LIQUIDITY_GROWTH_FACTOR
);
}
return TradingLiquidityAction({ update: true, newAmount: targetBNTTradingLiquidity });
}
/**
* @dev adjusts the trading liquidity based on the base token vault balance and funding limits
*/
function _updateTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
PoolLiquidity memory liquidity,
Fraction memory fundingRate,
uint256 minLiquidityForTrading
) private {
// ensure that the base token reserve isn't empty
uint256 tokenReserveAmount = pool.balanceOf(address(_masterVault));
if (tokenReserveAmount == 0) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
if (_poolRateState(liquidity, data.averageRate) == PoolRateState.Unstable) {
return;
}
if (!fundingRate.isPositive()) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
TradingLiquidityAction memory action = _calcTargetBNTTradingLiquidity(
tokenReserveAmount,
_bntPool.availableFunding(pool),
liquidity,
fundingRate,
minLiquidityForTrading
);
if (!action.update) {
return;
}
if (action.newAmount == 0) {
_resetTradingLiquidity(contextId, pool, data, TRADING_STATUS_UPDATE_MIN_LIQUIDITY);
return;
}
// update funding from the BNT pool
if (action.newAmount > liquidity.bntTradingLiquidity) {
_bntPool.requestFunding(contextId, pool, action.newAmount - liquidity.bntTradingLiquidity);
} else if (action.newAmount < liquidity.bntTradingLiquidity) {
_bntPool.renounceFunding(contextId, pool, liquidity.bntTradingLiquidity - action.newAmount);
}
// calculate the base token trading liquidity based on the new BNT trading liquidity and the effective
// funding rate (please note that the effective funding rate is always the rate between BNT and the base token)
uint256 baseTokenTradingLiquidity = MathEx.mulDivF(action.newAmount, fundingRate.d, fundingRate.n);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
PoolLiquidity memory newLiquidity = PoolLiquidity({
bntTradingLiquidity: SafeCast.toUint128(action.newAmount),
baseTokenTradingLiquidity: SafeCast.toUint128(baseTokenTradingLiquidity),
stakedBalance: liquidity.stakedBalance
});
// update the liquidity data of the pool
data.liquidity = newLiquidity;
_dispatchTradingLiquidityEvents(contextId, pool, data.poolToken.totalSupply(), liquidity, newLiquidity);
}
function _dispatchTradingLiquidityEvents(
bytes32 contextId,
Token pool,
PoolLiquidity memory prevLiquidity,
PoolLiquidity memory newLiquidity
) private {
if (newLiquidity.bntTradingLiquidity != prevLiquidity.bntTradingLiquidity) {
emit TradingLiquidityUpdated({
contextId: contextId,
pool: pool,
token: Token(address(_bnt)),
prevLiquidity: prevLiquidity.bntTradingLiquidity,
newLiquidity: newLiquidity.bntTradingLiquidity
});
}
if (newLiquidity.baseTokenTradingLiquidity != prevLiquidity.baseTokenTradingLiquidity) {
emit TradingLiquidityUpdated({
contextId: contextId,
pool: pool,
token: pool,
prevLiquidity: prevLiquidity.baseTokenTradingLiquidity,
newLiquidity: newLiquidity.baseTokenTradingLiquidity
});
}
}
function _dispatchTradingLiquidityEvents(
bytes32 contextId,
Token pool,
uint256 poolTokenTotalSupply,
PoolLiquidity memory prevLiquidity,
PoolLiquidity memory newLiquidity
) private {
_dispatchTradingLiquidityEvents(contextId, pool, prevLiquidity, newLiquidity);
if (newLiquidity.stakedBalance != prevLiquidity.stakedBalance) {
emit TotalLiquidityUpdated({
contextId: contextId,
pool: pool,
liquidity: pool.balanceOf(address(_masterVault)),
stakedBalance: newLiquidity.stakedBalance,
poolTokenSupply: poolTokenTotalSupply
});
}
}
/**
* @dev resets trading liquidity and renounces any remaining BNT funding
*/
function _resetTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
uint8 reason
) private {
_resetTradingLiquidity(contextId, pool, data, data.liquidity.bntTradingLiquidity, reason);
}
/**
* @dev resets trading liquidity and renounces any remaining BNT funding
*/
function _resetTradingLiquidity(
bytes32 contextId,
Token pool,
Pool storage data,
uint256 currentBNTTradingLiquidity,
uint8 reason
) private {
// reset the network and base token trading liquidities
data.liquidity.bntTradingLiquidity = 0;
data.liquidity.baseTokenTradingLiquidity = 0;
// reset the recent average rage
data.averageRate = AverageRate({ blockNumber: 0, rate: zeroFraction112() });
// ensure that trading is disabled
if (data.tradingEnabled) {
data.tradingEnabled = false;
emit TradingEnabled({ pool: pool, newStatus: false, reason: reason });
}
// renounce all network liquidity
if (currentBNTTradingLiquidity > 0) {
_bntPool.renounceFunding(contextId, pool, currentBNTTradingLiquidity);
}
}
/**
* @dev returns initial trading params
*/
function _initTrade(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 amount,
uint256 limit,
bool bySourceAmount
) private view returns (TradeIntermediateResult memory result) {
// ensure that BNT is either the source or the target token
bool isSourceBNT = sourceToken.isEqual(_bnt);
bool isTargetBNT = targetToken.isEqual(_bnt);
if (isSourceBNT && !isTargetBNT) {
result.isSourceBNT = true;
result.pool = targetToken;
} else if (!isSourceBNT && isTargetBNT) {
result.isSourceBNT = false;
result.pool = sourceToken;
} else {
// BNT isn't one of the tokens or is both of them
revert DoesNotExist();
}
Pool storage data = _poolStorage(result.pool);
// verify that trading is enabled
if (!data.tradingEnabled) {
revert TradingDisabled();
}
result.contextId = contextId;
result.bySourceAmount = bySourceAmount;
if (result.bySourceAmount) {
result.sourceAmount = amount;
} else {
result.targetAmount = amount;
}
result.limit = limit;
result.tradingFeePPM = data.tradingFeePPM;
PoolLiquidity memory liquidity = data.liquidity;
if (result.isSourceBNT) {
result.sourceBalance = liquidity.bntTradingLiquidity;
result.targetBalance = liquidity.baseTokenTradingLiquidity;
} else {
result.sourceBalance = liquidity.baseTokenTradingLiquidity;
result.targetBalance = liquidity.bntTradingLiquidity;
}
result.stakedBalance = liquidity.stakedBalance;
}
/**
* @dev returns trade amount and fee by providing the source amount
*/
function _tradeAmountAndFeeBySourceAmount(
uint256 sourceBalance,
uint256 targetBalance,
uint32 tradingFeePPM,
uint256 sourceAmount
) private pure returns (TradeAmountAndTradingFee memory) {
if (sourceBalance == 0 || targetBalance == 0) {
revert InsufficientLiquidity();
}
uint256 targetAmount = MathEx.mulDivF(targetBalance, sourceAmount, sourceBalance + sourceAmount);
uint256 tradingFeeAmount = MathEx.mulDivF(targetAmount, tradingFeePPM, PPM_RESOLUTION);
return
TradeAmountAndTradingFee({ amount: targetAmount - tradingFeeAmount, tradingFeeAmount: tradingFeeAmount });
}
/**
* @dev returns trade amount and fee by providing either the target amount
*/
function _tradeAmountAndFeeByTargetAmount(
uint256 sourceBalance,
uint256 targetBalance,
uint32 tradingFeePPM,
uint256 targetAmount
) private pure returns (TradeAmountAndTradingFee memory) {
if (sourceBalance == 0) {
revert InsufficientLiquidity();
}
uint256 tradingFeeAmount = MathEx.mulDivF(targetAmount, tradingFeePPM, PPM_RESOLUTION - tradingFeePPM);
uint256 fullTargetAmount = targetAmount + tradingFeeAmount;
uint256 sourceAmount = MathEx.mulDivF(sourceBalance, fullTargetAmount, targetBalance - fullTargetAmount);
return TradeAmountAndTradingFee({ amount: sourceAmount, tradingFeeAmount: tradingFeeAmount });
}
/**
* @dev processes a trade by providing either the source or the target amount and updates the in-memory intermediate
* result
*/
function _processTrade(TradeIntermediateResult memory result) private view {
TradeAmountAndTradingFee memory tradeAmountAndFee;
if (result.bySourceAmount) {
tradeAmountAndFee = _tradeAmountAndFeeBySourceAmount(
result.sourceBalance,
result.targetBalance,
result.tradingFeePPM,
result.sourceAmount
);
result.targetAmount = tradeAmountAndFee.amount;
// ensure that the target amount is above the requested minimum return amount
if (result.targetAmount < result.limit) {
revert InsufficientTargetAmount();
}
} else {
tradeAmountAndFee = _tradeAmountAndFeeByTargetAmount(
result.sourceBalance,
result.targetBalance,
result.tradingFeePPM,
result.targetAmount
);
result.sourceAmount = tradeAmountAndFee.amount;
// ensure that the user has provided enough tokens to make the trade
if (result.sourceAmount > result.limit) {
revert InsufficientSourceAmount();
}
}
result.tradingFeeAmount = tradeAmountAndFee.tradingFeeAmount;
// sync the trading and staked balance
result.sourceBalance += result.sourceAmount;
result.targetBalance -= result.targetAmount;
if (result.isSourceBNT) {
result.stakedBalance += result.tradingFeeAmount;
}
_processNetworkFee(result);
}
/**
* @dev processes the network fee and updates the in-memory intermediate result
*/
function _processNetworkFee(TradeIntermediateResult memory result) private view {
uint32 networkFeePPM = _networkSettings.networkFeePPM();
if (networkFeePPM == 0) {
return;
}
// calculate the target network fee amount
uint256 targetNetworkFeeAmount = MathEx.mulDivF(result.tradingFeeAmount, networkFeePPM, PPM_RESOLUTION);
// update the target balance (but don't deduct it from the full trading fee amount)
result.targetBalance -= targetNetworkFeeAmount;
if (!result.isSourceBNT) {
result.networkFeeAmount = targetNetworkFeeAmount;
return;
}
// trade the network fee (taken from the base token) to BNT
result.networkFeeAmount = _tradeAmountAndFeeBySourceAmount(
result.targetBalance,
result.sourceBalance,
0,
targetNetworkFeeAmount
).amount;
// since we have received the network fee in base tokens and have traded them for BNT (so that the network fee
// is always kept in BNT), we'd need to adapt the trading liquidity and the staked balance accordingly
result.targetBalance += targetNetworkFeeAmount;
result.sourceBalance -= result.networkFeeAmount;
result.stakedBalance -= targetNetworkFeeAmount;
}
/**
* @dev performs a trade
*/
function _performTrade(TradeIntermediateResult memory result) private {
Pool storage data = _poolData[result.pool];
PoolLiquidity memory prevLiquidity = data.liquidity;
// update the recent average rate
_updateAverageRate(
data,
Fraction({ n: prevLiquidity.bntTradingLiquidity, d: prevLiquidity.baseTokenTradingLiquidity })
);
_processTrade(result);
// trading liquidity is assumed to never exceed 128 bits (the cast below will revert otherwise)
PoolLiquidity memory newLiquidity = PoolLiquidity({
bntTradingLiquidity: SafeCast.toUint128(result.isSourceBNT ? result.sourceBalance : result.targetBalance),
baseTokenTradingLiquidity: SafeCast.toUint128(
result.isSourceBNT ? result.targetBalance : result.sourceBalance
),
stakedBalance: result.stakedBalance
});
_dispatchTradingLiquidityEvents(result.contextId, result.pool, prevLiquidity, newLiquidity);
// update the liquidity data of the pool
data.liquidity = newLiquidity;
}
/**
* @dev returns the state of a pool's rate
*/
function _poolRateState(PoolLiquidity memory liquidity, AverageRate memory averageRateInfo)
internal
view
returns (PoolRateState)
{
Fraction memory spotRate = Fraction({
n: liquidity.bntTradingLiquidity,
d: liquidity.baseTokenTradingLiquidity
});
Fraction112 memory averageRate = averageRateInfo.rate;
if (!spotRate.isPositive() || !averageRate.isPositive()) {
return PoolRateState.Uninitialized;
}
if (averageRateInfo.blockNumber != _blockNumber()) {
averageRate = _calcAverageRate(averageRate, spotRate);
}
if (MathEx.isInRange(averageRate.fromFraction112(), spotRate, RATE_MAX_DEVIATION_PPM)) {
return PoolRateState.Stable;
}
return PoolRateState.Unstable;
}
/**
* @dev updates the average rate
*/
function _updateAverageRate(Pool storage data, Fraction memory spotRate) private {
uint32 blockNumber = _blockNumber();
if (data.averageRate.blockNumber != blockNumber) {
data.averageRate = AverageRate({
blockNumber: blockNumber,
rate: _calcAverageRate(data.averageRate.rate, spotRate)
});
}
}
/**
* @dev calculates the average rate
*/
function _calcAverageRate(Fraction112 memory averageRate, Fraction memory spotRate)
private
pure
returns (Fraction112 memory)
{
return
MathEx
.weightedAverage(averageRate.fromFraction112(), spotRate, EMA_AVERAGE_RATE_WEIGHT, EMA_SPOT_RATE_WEIGHT)
.toFraction112();
}
/**
* @dev verifies if the provided rate is valid
*/
function _validRate(Fraction memory rate) internal pure {
if (!rate.isPositive()) {
revert InvalidRate();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION as M } from "../utility/Constants.sol";
import { Sint256, Uint512, MathEx } from "../utility/MathEx.sol";
error PoolCollectionWithdrawalInputInvalid();
/**
* @dev This library implements the mathematics behind base-token withdrawal.
* It exposes a single function which takes the following input values:
* `a` - BNT trading liquidity
* `b` - base token trading liquidity
* `c` - base token excess amount
* `e` - base token staked amount
* `w` - base token external protection vault balance
* `m` - trading fee in PPM units
* `n` - withdrawal fee in PPM units
* `x` - base token withdrawal amount
* And returns the following output values:
* `p` - BNT amount to add to the trading liquidity and to the master vault
* `q` - BNT amount to add to the protocol equity
* `r` - base token amount to add to the trading liquidity
* `s` - base token amount to transfer from the master vault to the provider
* `t` - BNT amount to mint directly for the provider
* `u` - base token amount to transfer from the external protection vault to the provider
* `v` - base token amount to keep in the pool as a withdrawal fee
* The following table depicts the actual formulae based on the current state of the system:
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | Deficit | Surplus |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = a*x*(e*(1-n)-b-c)*(1-m)/(b*e-x*(e*(1-n)-b-c)*(1-m)) | p = -a*x*(b+c-e*(1-n))/(b*e*(1-m)+x*(b+c-e*(1-n))*(1-m)) |
* | | q = 0 | q = 0 |
* | | r = -x*(e*(1-n)-b-c)/e | r = x*(b+c-e*(1-n))/e |
* | Arbitrage | s = x*(1-n) | s = x*(1-n) |
* | | t = 0 | t = 0 |
* | | u = 0 | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = -a*z/(b*e) where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | p = -a*z/b where z = max(x*(1-n)-c,0) |
* | | q = -a*z/(b*e) where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | q = -a*z/b where z = max(x*(1-n)-c,0) |
* | | r = -z/e where z = max(x*(1-n)*b-c*(e-x*(1-n)),0) | r = -z where z = max(x*(1-n)-c,0) |
* | Default | s = x*(1-n)*(b+c)/e | s = x*(1-n) |
* | | t = see function `externalProtection` | t = 0 |
* | | u = see function `externalProtection` | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* | | p = 0 | p = 0 |
* | | q = 0 | q = 0 |
* | | r = 0 | r = 0 |
* | Bootstrap | s = x*(1-n)*c/e | s = x*(1-n) |
* | | t = see function `externalProtection` | t = 0 |
* | | u = see function `externalProtection` | u = 0 |
* | | v = x*n | v = x*n |
* +-----------+---------------------------------------------------------+----------------------------------------------------------+
* Note that for the sake of illustration, both `m` and `n` are assumed normalized (between 0 and 1).
* During runtime, it is taken into account that they are given in PPM units (between 0 and 1000000).
*/
library PoolCollectionWithdrawal {
using MathEx for uint256;
struct Output {
Sint256 p;
Sint256 q;
Sint256 r;
uint256 s;
uint256 t;
uint256 u;
uint256 v;
}
/**
* @dev returns `p`, `q`, `r`, `s`, `t`, `u` and `v` according to the current state:
* +-------------------+-----------------------------------------------------------+
* | `e > (b+c)/(1-n)` | bootstrap deficit or default deficit or arbitrage deficit |
* +-------------------+-----------------------------------------------------------+
* | `e < (b+c)` | bootstrap surplus or default surplus or arbitrage surplus |
* +-------------------+-----------------------------------------------------------+
* | otherwise | bootstrap surplus or default surplus |
* +-------------------+-----------------------------------------------------------+
*/
function calculateWithdrawalAmounts(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 w, // <= 2**128-1
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// <= e <= 2**128-1
) internal pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
if (
a > type(uint128).max ||
b > type(uint128).max ||
c > type(uint128).max ||
e > type(uint128).max ||
w > type(uint128).max ||
m > M ||
n > M ||
x > e
) {
revert PoolCollectionWithdrawalInputInvalid();
}
uint256 y = (x * (M - n)) / M;
if ((e * (M - n)) / M > b + c) {
uint256 f = (e * (M - n)) / M - (b + c);
uint256 g = e - (b + c);
if (isStable(b, c, e, x) && affordableDeficit(b, e, f, g, m, n, x)) {
output = arbitrageDeficit(a, b, e, f, m, x, y);
} else if (a > 0) {
output = defaultDeficit(a, b, c, e, y);
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
} else {
output.s = (y * c) / e;
(output.t, output.u) = externalProtection(a, b, e, g, y, w);
}
} else {
uint256 f = MathEx.subMax0(b + c, e);
if (f > 0 && isStable(b, c, e, x) && affordableSurplus(b, e, f, m, n, x)) {
output = arbitrageSurplus(a, b, e, f, m, n, x, y);
} else if (a > 0) {
output = defaultSurplus(a, b, c, y);
} else {
output.s = y;
}
}
output.v = x - y;
}
/**
* @dev returns `x < e*c/(b+c)`
*/
function isStable(
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 x /// <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
return b * x < c * (e - x);
}
/**
* @dev returns `b*e*((e*(1-n)-b-c)*m+e*n) > (e*(1-n)-b-c)*x*(e-b-c)*(1-m)`
*/
function affordableDeficit(
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == e*(1-n)-b-c <= e <= 2**128-1
uint256 g, // == e-b-c <= e <= 2**128-1
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// < e*c/(b+c) <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
Uint512 memory lhs = MathEx.mul512(b * e, f * m + e * n);
Uint512 memory rhs = MathEx.mul512(f * x, g * (M - m));
return MathEx.gt512(lhs, rhs);
}
/**
* @dev returns `b*e*((b+c-e)*m+e*n) > (b+c-e)*x*(b+c-e*(1-n))*(1-m)`
*/
function affordableSurplus(
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == b+c-e <= 2**129-2
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x /// < e*c/(b+c) <= e <= 2**128-1
) private pure returns (bool) {
// given the restrictions above, everything below can be declared `unchecked`
Uint512 memory lhs = MathEx.mul512(b * e, (f * m + e * n) * M);
Uint512 memory rhs = MathEx.mul512(f * x, (f * M + e * n) * (M - m));
return MathEx.gt512(lhs, rhs); // `x < e*c/(b+c)` --> `f*x < e*c*(b+c-e)/(b+c) <= e*c <= 2**256-1`
}
/**
* @dev returns:
* `p = a*x*(e*(1-n)-b-c)*(1-m)/(b*e-x*(e*(1-n)-b-c)*(1-m))`
* `q = 0`
* `r = -x*(e*(1-n)-b-c)/e`
* `s = x*(1-n)`
*/
function arbitrageDeficit(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == e*(1-n)-b-c <= e <= 2**128-1
uint256 m, // <= M == 1000000
uint256 x, // <= e <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 i = f * (M - m);
uint256 j = mulSubMulDivF(b, e * M, x, i, 1);
output.p = MathEx.mulDivF(a * x, i, j).toPos256();
output.r = MathEx.mulDivF(x, f, e).toNeg256();
output.s = y;
}
/**
* @dev returns:
* `p = -a*x*(b+c-e*(1-n))/(b*e*(1-m)+x*(b+c-e*(1-n))*(1-m))`
* `q = 0`
* `r = x*(b+c-e*(1-n))/e`
* `s = x*(1-n)`
*/
function arbitrageSurplus(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 f, // == b+c-e <= 2**129-2
uint256 m, // <= M == 1000000
uint256 n, // <= M == 1000000
uint256 x, // <= e <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 i = f * M + e * n;
uint256 j = mulAddMulDivF(b, e * (M - m), x, i * (M - m), M);
output.p = MathEx.mulDivF(a * x, i, j).toNeg256();
output.r = MathEx.mulDivF(x, i, e * M).toPos256();
output.s = y;
}
/**
* @dev returns:
* `p = -a*z/(b*e)` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `q = -a*z/(b*e)` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `r = -z/e` where `z = max(x*(1-n)*b-c*(e-x*(1-n)),0)`
* `s = x*(1-n)*(b+c)/e`
*/
function defaultDeficit(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 z = MathEx.subMax0(y * b, c * (e - y));
output.p = MathEx.mulDivF(a, z, b * e).toNeg256();
output.q = output.p;
output.r = (z / e).toNeg256();
output.s = MathEx.mulDivF(y, b + c, e);
}
/**
* @dev returns:
* `p = -a*z/b` where `z = max(x*(1-n)-c,0)`
* `q = -a*z/b` where `z = max(x*(1-n)-c,0)`
* `r = -z` where `z = max(x*(1-n)-c,0)`
* `s = x*(1-n)`
*/
function defaultSurplus(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 c, // <= 2**128-1
uint256 y /// == x*(1-n) <= x <= e <= 2**128-1
) private pure returns (Output memory output) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 z = MathEx.subMax0(y, c);
output.p = MathEx.mulDivF(a, z, b).toNeg256();
output.q = output.p;
output.r = z.toNeg256();
output.s = y;
}
/**
* @dev returns `t` and `u` according to the current state:
* +-----------------------+-------+---------------------------+-------------------+
* | x*(1-n)*(e-b-c)/e > w | a > 0 | t | u |
* +-----------------------+-------+---------------------------+-------------------+
* | true | true | a*(x*(1-n)*(e-b-c)/e-w)/b | w |
* +-----------------------+-------+---------------------------+-------------------+
* | true | false | 0 | w |
* +-----------------------+-------+---------------------------+-------------------+
* | false | true | 0 | x*(1-n)*(e-b-c)/e |
* +-----------------------+-------+---------------------------+-------------------+
* | false | false | 0 | x*(1-n)*(e-b-c)/e |
* +-----------------------+-------+---------------------------+-------------------+
*/
function externalProtection(
uint256 a, // <= 2**128-1
uint256 b, // <= 2**128-1
uint256 e, // <= 2**128-1
uint256 g, // == e-b-c <= e <= 2**128-1
uint256 y, // == x*(1-n) <= x <= e <= 2**128-1
uint256 w /// <= 2**128-1
) private pure returns (uint256 t, uint256 u) {
// given the restrictions above, everything below can be declared `unchecked`
uint256 yg = y * g;
uint256 we = w * e;
if (yg > we) {
t = a > 0 ? MathEx.mulDivF(a, yg - we, b * e) : 0;
u = w;
} else {
t = 0;
u = yg / e;
}
}
/**
* @dev returns `a*b+x*y/z`
*/
function mulAddMulDivF(
uint256 a,
uint256 b,
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return a * b + MathEx.mulDivF(x, y, z);
}
/**
* @dev returns `a*b-x*y/z`
*/
function mulSubMulDivF(
uint256 a,
uint256 b,
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return a * b - MathEx.mulDivF(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IPoolToken } from "./IPoolToken.sol";
import { Token } from "../../token/Token.sol";
import { IVault } from "../../vaults/interfaces/IVault.sol";
// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");
// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");
// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");
// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");
/**
* @dev BNT Pool interface
*/
interface IBNTPool is IVault {
/**
* @dev returns the BNT pool token contract
*/
function poolToken() external view returns (IPoolToken);
/**
* @dev returns the total staked BNT balance in the network
*/
function stakedBalance() external view returns (uint256);
/**
* @dev returns the current funding of given pool
*/
function currentPoolFunding(Token pool) external view returns (uint256);
/**
* @dev returns the available BNT funding for a given pool
*/
function availableFunding(Token pool) external view returns (uint256);
/**
* @dev converts the specified pool token amount to the underlying BNT amount
*/
function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying BNT amount to pool token amount
*/
function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);
/**
* @dev mints BNT to the recipient
*
* requirements:
*
* - the caller must have the ROLE_BNT_MANAGER role
*/
function mint(address recipient, uint256 bntAmount) external;
/**
* @dev burns BNT from the vault
*
* requirements:
*
* - the caller must have the ROLE_VAULT_MANAGER role
*/
function burnFromVault(uint256 bntAmount) external;
/**
* @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - BNT tokens must have been already deposited into the contract
*/
function depositFor(
bytes32 contextId,
address provider,
uint256 bntAmount,
bool isMigrating,
uint256 originalVBNTAmount
) external returns (uint256);
/**
* @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
*
* requirements:
*
* - the caller must be the network contract
* - VBNT token must have been already deposited into the contract
*/
function withdraw(
bytes32 contextId,
address provider,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the withdrawn BNT amount
*/
function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev requests BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the request amount should be below the funding limit for a given pool
* - the average rate of the pool must not deviate too much from its spot rate
*/
function requestFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev renounces BNT funding
*
* requirements:
*
* - the caller must have the ROLE_FUNDING_MANAGER role
* - the token must have been whitelisted
* - the average rate of the pool must not deviate too much from its spot rate
*/
function renounceFunding(
bytes32 contextId,
Token pool,
uint256 bntAmount
) external;
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(
Token pool,
uint256 feeAmount,
bool isTradeFee
) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";
import { Token } from "../../token/Token.sol";
import { IPoolToken } from "./IPoolToken.sol";
struct PoolLiquidity {
uint128 bntTradingLiquidity; // the BNT trading liquidity
uint128 baseTokenTradingLiquidity; // the base token trading liquidity
uint256 stakedBalance; // the staked balance
}
struct AverageRate {
uint32 blockNumber;
Fraction112 rate;
}
struct Pool {
IPoolToken poolToken; // the pool token of the pool
uint32 tradingFeePPM; // the trading fee (in units of PPM)
bool tradingEnabled; // whether trading is enabled
bool depositingEnabled; // whether depositing is enabled
AverageRate averageRate; // the recent average rate
uint256 depositLimit; // the deposit limit
PoolLiquidity liquidity; // the overall liquidity in the pool
}
struct WithdrawalAmounts {
uint256 totalAmount;
uint256 baseTokenAmount;
uint256 bntAmount;
}
// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
struct TradeAmountAndFee {
uint256 amount; // the source/target amount (depending on the context) resulting from the trade
uint256 tradingFeeAmount; // the trading fee amount
uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}
/**
* @dev Pool Collection interface
*/
interface IPoolCollection is IVersioned {
/**
* @dev returns the type of the pool
*/
function poolType() external pure returns (uint16);
/**
* @dev returns the default trading fee (in units of PPM)
*/
function defaultTradingFeePPM() external view returns (uint32);
/**
* @dev returns all the pools which are managed by this pool collection
*/
function pools() external view returns (Token[] memory);
/**
* @dev returns the number of all the pools which are managed by this pool collection
*/
function poolCount() external view returns (uint256);
/**
* @dev returns whether a pool is valid
*/
function isPoolValid(Token pool) external view returns (bool);
/**
* @dev returns specific pool's data
*/
function poolData(Token pool) external view returns (Pool memory);
/**
* @dev returns the overall liquidity in the pool
*/
function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);
/**
* @dev returns the pool token of the pool
*/
function poolToken(Token pool) external view returns (IPoolToken);
/**
* @dev converts the specified pool token amount to the underlying base token amount
*/
function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);
/**
* @dev converts the specified underlying base token amount to pool token amount
*/
function underlyingToPoolToken(Token pool, uint256 tokenAmount) external view returns (uint256);
/**
* @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
* amount
*/
function poolTokenAmountToBurn(
Token pool,
uint256 tokenAmountToDistribute,
uint256 protocolPoolTokenAmount
) external view returns (uint256);
/**
* @dev creates a new pool
*
* requirements:
*
* - the caller must be the network contract
* - the pool should have been whitelisted
* - the pool isn't already defined in the collection
*/
function createPool(Token token) external;
/**
* @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
*
* requirements:
*
* - the caller must be the network contract
* - assumes that the base token has been already deposited in the vault
*/
function depositFor(
bytes32 contextId,
address provider,
Token pool,
uint256 tokenAmount
) external returns (uint256);
/**
* @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
*
* requirements:
*
* - the caller must be the network contract
* - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
*/
function withdraw(
bytes32 contextId,
address provider,
Token pool,
uint256 poolTokenAmount
) external returns (uint256);
/**
* @dev returns the amounts that would be returned if the position is currently withdrawn,
* along with the breakdown of the base token and the BNT compensation
*/
function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);
/**
* @dev performs a trade by providing the source amount and returns the target amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeBySourceAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 sourceAmount,
uint256 minReturnAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
*
* requirements:
*
* - the caller must be the network contract
*/
function tradeByTargetAmount(
bytes32 contextId,
Token sourceToken,
Token targetToken,
uint256 targetAmount,
uint256 maxSourceAmount
) external returns (TradeAmountAndFee memory);
/**
* @dev returns the output amount and fee when trading by providing the source amount
*/
function tradeOutputAndFeeBySourceAmount(
Token sourceToken,
Token targetToken,
uint256 sourceAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev returns the input amount and fee when trading by providing the target amount
*/
function tradeInputAndFeeByTargetAmount(
Token sourceToken,
Token targetToken,
uint256 targetAmount
) external view returns (TradeAmountAndFee memory);
/**
* @dev notifies the pool of accrued fees
*
* requirements:
*
* - the caller must be the network contract
*/
function onFeesCollected(Token pool, uint256 feeAmount) external;
/**
* @dev migrates a pool to this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolIn(Token pool, Pool calldata data) external;
/**
* @dev migrates a pool from this pool collection
*
* requirements:
*
* - the caller must be the pool migrator contract
*/
function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IPoolCollection } from "./IPoolCollection.sol";
/**
* @dev Pool Migrator interface
*/
interface IPoolMigrator is IVersioned {
/**
* @dev migrates a pool and returns the new pool collection it exists in
*
* notes:
*
* - invalid or incompatible pools will be skipped gracefully
*
* requirements:
*
* - the caller must be the network contract
*/
function migratePool(Token pool) external returns (IPoolCollection);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";
import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";
/**
* @dev Pool Token interface
*/
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
/**
* @dev returns the address of the reserve token
*/
function reserveToken() external view returns (Token);
/**
* @dev increases the token supply and sends the new tokens to the given account
*
* requirements:
*
* - the caller must be the owner of the contract
*/
function mint(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Token } from "../../token/Token.sol";
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { IPoolToken } from "./IPoolToken.sol";
/**
* @dev Pool Token Factory interface
*/
interface IPoolTokenFactory is IUpgradeable {
/**
* @dev returns the custom symbol override for a given reserve token
*/
function tokenSymbolOverride(Token token) external view returns (string memory);
/**
* @dev returns the custom decimals override for a given reserve token
*/
function tokenDecimalsOverride(Token token) external view returns (uint8);
/**
* @dev creates a pool token for the specified token
*/
function createPoolToken(Token token) external returns (IPoolToken);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/**
* @dev extends the SafeERC20 library with additional operations
*/
library SafeERC20Ex {
using SafeERC20 for IERC20;
/**
* @dev ensures that the spender has sufficient allowance
*/
function ensureApprove(
IERC20 token,
address spender,
uint256 amount
) internal {
if (amount == 0) {
return;
}
uint256 allowance = token.allowance(address(this), spender);
if (allowance >= amount) {
return;
}
if (allowance > 0) {
token.safeApprove(spender, 0);
}
token.safeApprove(spender, amount);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
* but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
*/
interface Token {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
import { SafeERC20Ex } from "./SafeERC20Ex.sol";
import { Token } from "./Token.sol";
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
}
/**
* @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
*/
library TokenLibrary {
using SafeERC20 for IERC20;
using SafeERC20Ex for IERC20;
error PermitUnsupported();
// the address that represents the native token reserve
address public constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// the symbol that represents the native token
string private constant NATIVE_TOKEN_SYMBOL = "ETH";
// the decimals for the native token
uint8 private constant NATIVE_TOKEN_DECIMALS = 18;
/**
* @dev returns whether the provided token represents an ERC20 or the native token reserve
*/
function isNative(Token token) internal pure returns (bool) {
return address(token) == NATIVE_TOKEN_ADDRESS;
}
/**
* @dev returns the symbol of the native token/ERC20 token
*/
function symbol(Token token) internal view returns (string memory) {
if (isNative(token)) {
return NATIVE_TOKEN_SYMBOL;
}
return toERC20(token).symbol();
}
/**
* @dev returns the decimals of the native token/ERC20 token
*/
function decimals(Token token) internal view returns (uint8) {
if (isNative(token)) {
return NATIVE_TOKEN_DECIMALS;
}
return toERC20(token).decimals();
}
/**
* @dev returns the balance of the native token/ERC20 token
*/
function balanceOf(Token token, address account) internal view returns (uint256) {
if (isNative(token)) {
return account.balance;
}
return toIERC20(token).balanceOf(account);
}
/**
* @dev transfers a specific amount of the native token/ERC20 token
*/
function safeTransfer(
Token token,
address to,
uint256 amount
) internal {
if (amount == 0) {
return;
}
if (isNative(token)) {
payable(to).transfer(amount);
} else {
toIERC20(token).safeTransfer(to, amount);
}
}
/**
* @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
*
* note that the function does not perform any action if the native token is provided
*/
function safeTransferFrom(
Token token,
address from,
address to,
uint256 amount
) internal {
if (amount == 0 || isNative(token)) {
return;
}
toIERC20(token).safeTransferFrom(from, to, amount);
}
/**
* @dev approves a specific amount of the native token/ERC20 token from a specific holder
*
* note that the function does not perform any action if the native token is provided
*/
function safeApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).safeApprove(spender, amount);
}
/**
* @dev ensures that the spender has sufficient allowance
*
* note that the function does not perform any action if the native token is provided
*/
function ensureApprove(
Token token,
address spender,
uint256 amount
) internal {
if (isNative(token)) {
return;
}
toIERC20(token).ensureApprove(spender, amount);
}
/**
* @dev performs an EIP2612 permit
*/
function permit(
Token token,
address owner,
address spender,
uint256 tokenAmount,
uint256 deadline,
Signature memory signature
) internal {
if (isNative(token)) {
revert PermitUnsupported();
}
// permit the amount the owner is trying to deposit. Please note, that if the base token doesn't support
// EIP2612 permit - either this call or the inner safeTransferFrom will revert
IERC20Permit(address(token)).permit(
owner,
spender,
tokenAmount,
deadline,
signature.v,
signature.r,
signature.s
);
}
/**
* @dev compares between a token and another raw ERC20 token
*/
function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
return toIERC20(token) == erc20Token;
}
/**
* @dev utility function that converts an token to an IERC20
*/
function toIERC20(Token token) internal pure returns (IERC20) {
return IERC20(address(token));
}
/**
* @dev utility function that converts an token to an ERC20
*/
function toERC20(Token token) internal pure returns (ERC20) {
return ERC20(address(token));
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev burnable ERC20 interface
*/
interface IERC20Burnable {
/**
* @dev Destroys tokens from the caller.
*/
function burn(uint256 amount) external;
/**
* @dev Destroys tokens from a recipient, deducting from the caller's allowance
*
* requirements:
*
* - the caller must have allowance for recipient's tokens of at least the specified amount
*/
function burnFrom(address recipient, uint256 amount) external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev this contract abstracts the block number in order to allow for more flexible control in tests
*/
contract BlockNumber {
/**
* @dev returns the current block-number
*/
function _blockNumber() internal view virtual returns (uint32) {
return uint32(block.number);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
uint32 constant PPM_RESOLUTION = 1000000;
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
struct Fraction {
uint256 n;
uint256 d;
}
struct Fraction112 {
uint112 n;
uint112 d;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Fraction, Fraction112 } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";
// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
return Fraction({ n: 0, d: 1 });
}
// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
return Fraction112({ n: 0, d: 1 });
}
/**
* @dev this library provides a set of fraction operations
*/
library FractionLibrary {
/**
* @dev returns whether a standard fraction is valid
*/
function isValid(Fraction memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a standard fraction is positive
*/
function isPositive(Fraction memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev returns whether a 112-bit fraction is valid
*/
function isValid(Fraction112 memory fraction) internal pure returns (bool) {
return fraction.d != 0;
}
/**
* @dev returns whether a 112-bit fraction is positive
*/
function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
return isValid(fraction) && fraction.n != 0;
}
/**
* @dev reduces a standard fraction to a 112-bit fraction
*/
function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);
return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
}
/**
* @dev expands a 112-bit fraction to a standard fraction
*/
function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
return Fraction({ n: fraction.n, d: fraction.d });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction } from "./Fraction.sol";
import { PPM_RESOLUTION } from "./Constants.sol";
uint256 constant ONE = 0x80000000000000000000000000000000;
uint256 constant LN2 = 0x58b90bfbe8e7bcd5e4f1d9cc01f97b57;
struct Uint512 {
uint256 hi; // 256 most significant bits
uint256 lo; // 256 least significant bits
}
struct Sint256 {
uint256 value;
bool isNeg;
}
/**
* @dev this library provides a set of complex math operations
*/
library MathEx {
error Overflow();
/**
* @dev returns `2 ^ f` by calculating `e ^ (f * ln(2))`, where `e` is Euler's number:
* - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
* - The exponentiation of each binary exponent is given (pre-calculated)
* - The exponentiation of r is calculated via Taylor series for e^x, where x = r
* - The exponentiation of the input is calculated by multiplying the intermediate results above
* - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
*/
function exp2(Fraction memory f) internal pure returns (Fraction memory) {
uint256 x = MathEx.mulDivF(LN2, f.n, f.d);
uint256 y;
uint256 z;
uint256 n;
if (x >= (ONE << 4)) {
revert Overflow();
}
unchecked {
z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
z = (z * y) / ONE;
n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
z = (z * y) / ONE;
n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
z = (z * y) / ONE;
n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
z = (z * y) / ONE;
n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
z = (z * y) / ONE;
n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
z = (z * y) / ONE;
n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
z = (z * y) / ONE;
n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
z = (z * y) / ONE;
n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
z = (z * y) / ONE;
n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
z = (z * y) / ONE;
n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
z = (z * y) / ONE;
n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
z = (z * y) / ONE;
n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
z = (z * y) / ONE;
n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
z = (z * y) / ONE;
n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
z = (z * y) / ONE;
n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
z = (z * y) / ONE;
n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
z = (z * y) / ONE;
n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
z = (z * y) / ONE;
n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
z = (z * y) / ONE;
n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!
if ((x & (ONE >> 3)) != 0)
n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3)
if ((x & (ONE >> 2)) != 0)
n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2)
if ((x & (ONE >> 1)) != 0)
n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1)
if ((x & (ONE << 0)) != 0)
n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0)
if ((x & (ONE << 1)) != 0)
n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1)
if ((x & (ONE << 2)) != 0)
n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2)
if ((x & (ONE << 3)) != 0)
n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3)
}
return Fraction({ n: n, d: ONE });
}
/**
* @dev returns a fraction with reduced components
*/
function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
return Fraction({ n: fraction.n / scale, d: fraction.d / scale });
}
/**
* @dev returns the weighted average of two fractions
*/
function weightedAverage(
Fraction memory fraction1,
Fraction memory fraction2,
uint256 weight1,
uint256 weight2
) internal pure returns (Fraction memory) {
return
Fraction({
n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
d: fraction1.d * fraction2.d * (weight1 + weight2)
});
}
/**
* @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
* for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
*/
function isInRange(
Fraction memory baseSample,
Fraction memory offsetSample,
uint32 maxDeviationPPM
) internal pure returns (bool) {
Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
return lte512(min, mid) && lte512(mid, max);
}
/**
* @dev returns an `Sint256` positive representation of an unsigned integer
*/
function toPos256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: false });
}
/**
* @dev returns an `Sint256` negative representation of an unsigned integer
*/
function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
return Sint256({ value: n, isNeg: true });
}
/**
* @dev returns the largest integer smaller than or equal to `x * y / z`
*/
function mulDivF(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
Uint512 memory xy = mul512(x, y);
// if `x * y < 2 ^ 256`
if (xy.hi == 0) {
return xy.lo / z;
}
// assert `x * y / z < 2 ^ 256`
if (xy.hi >= z) {
revert Overflow();
}
uint256 m = _mulMod(x, y, z); // `m = x * y % z`
Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`
// if `n < 2 ^ 256`
if (n.hi == 0) {
return n.lo / z;
}
uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
}
/**
* @dev returns the smallest integer larger than or equal to `x * y / z`
*/
function mulDivC(
uint256 x,
uint256 y,
uint256 z
) internal pure returns (uint256) {
uint256 w = mulDivF(x, y, z);
if (_mulMod(x, y, z) > 0) {
if (w >= type(uint256).max) {
revert Overflow();
}
return w + 1;
}
return w;
}
/**
* @dev returns the maximum of `n1 - n2` and 0
*/
function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
return n1 > n2 ? n1 - n2 : 0;
}
/**
* @dev returns the value of `x > y`
*/
function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
}
/**
* @dev returns the value of `x < y`
*/
function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
}
/**
* @dev returns the value of `x >= y`
*/
function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !lt512(x, y);
}
/**
* @dev returns the value of `x <= y`
*/
function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
return !gt512(x, y);
}
/**
* @dev returns the value of `x * y`
*/
function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
uint256 p = _mulModMax(x, y);
uint256 q = _unsafeMul(x, y);
if (p >= q) {
return Uint512({ hi: p - q, lo: q });
}
return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
}
/**
* @dev returns the value of `x - y`, given that `x >= y`
*/
function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
if (x.lo >= y) {
return Uint512({ hi: x.hi, lo: x.lo - y });
}
return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
}
/**
* @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
*/
function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
}
/**
* @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
*/
function _inv256(uint256 d) private pure returns (uint256) {
// approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
uint256 x = 1;
for (uint256 i = 0; i < 8; i++) {
x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
}
return x;
}
/**
* @dev returns `(x + y) % 2 ^ 256`
*/
function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x + y;
}
}
/**
* @dev returns `(x - y) % 2 ^ 256`
*/
function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x - y;
}
}
/**
* @dev returns `(x * y) % 2 ^ 256`
*/
function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
unchecked {
return x * y;
}
}
/**
* @dev returns `x * y % (2 ^ 256 - 1)`
*/
function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
return mulmod(x, y, type(uint256).max);
}
/**
* @dev returns `x * y % z`
*/
function _mulMod(
uint256 x,
uint256 y,
uint256 z
) private pure returns (uint256) {
return mulmod(x, y, z);
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IOwned } from "./interfaces/IOwned.sol";
import { AccessDenied } from "./Utils.sol";
/**
* @dev this contract provides support and utilities for contract ownership
*/
abstract contract Owned is IOwned {
error SameOwner();
address private _owner;
address private _newOwner;
/**
* @dev triggered when the owner is updated
*/
event OwnerUpdate(address indexed prevOwner, address indexed newOwner);
// solhint-disable func-name-mixedcase
/**
* @dev initializes the contract
*/
constructor() {
_transferOwnership(msg.sender);
}
// solhint-enable func-name-mixedcase
// allows execution by the owner only
modifier onlyOwner() {
_onlyOwner();
_;
}
// error message binary size optimization
function _onlyOwner() private view {
if (msg.sender != _owner) {
revert AccessDenied();
}
}
/**
* @inheritdoc IOwned
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @inheritdoc IOwned
*/
function transferOwnership(address ownerCandidate) public virtual onlyOwner {
if (ownerCandidate == _owner) {
revert SameOwner();
}
_newOwner = ownerCandidate;
}
/**
* @inheritdoc IOwned
*/
function acceptOwnership() public virtual {
if (msg.sender != _newOwner) {
revert AccessDenied();
}
_transferOwnership(_newOwner);
}
/**
* @dev returns the address of the new owner candidate
*/
function newOwner() external view returns (address) {
return _newOwner;
}
/**
* @dev sets the new owner internally
*/
function _transferOwnership(address ownerCandidate) private {
address prevOwner = _owner;
_owner = ownerCandidate;
_newOwner = address(0);
emit OwnerUpdate({ prevOwner: prevOwner, newOwner: ownerCandidate });
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { PPM_RESOLUTION } from "./Constants.sol";
error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidType();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();
/**
* @dev common utilities
*/
contract Utils {
// allows execution by the caller only
modifier only(address caller) {
_only(caller);
_;
}
function _only(address caller) internal view {
if (msg.sender != caller) {
revert AccessDenied();
}
}
// verifies that a value is greater than zero
modifier greaterThanZero(uint256 value) {
_greaterThanZero(value);
_;
}
// error message binary size optimization
function _greaterThanZero(uint256 value) internal pure {
if (value == 0) {
revert ZeroValue();
}
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address addr) {
_validAddress(addr);
_;
}
// error message binary size optimization
function _validAddress(address addr) internal pure {
if (addr == address(0)) {
revert InvalidAddress();
}
}
// validates an external address - currently only checks that it isn't null or this
modifier validExternalAddress(address addr) {
_validExternalAddress(addr);
_;
}
// error message binary size optimization
function _validExternalAddress(address addr) internal view {
if (addr == address(0) || addr == address(this)) {
revert InvalidExternalAddress();
}
}
// ensures that the fee is valid
modifier validFee(uint32 fee) {
_validFee(fee);
_;
}
// error message binary size optimization
function _validFee(uint32 fee) internal pure {
if (fee > PPM_RESOLUTION) {
revert InvalidFee();
}
}
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev Owned interface
*/
interface IOwned {
/**
* @dev returns the address of the current owner
*/
function owner() external view returns (address);
/**
* @dev allows transferring the contract ownership
*
* requirements:
*
* - the caller must be the owner of the contract
* - the new owner still needs to accept the transfer
*/
function transferOwnership(address ownerCandidate) external;
/**
* @dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() external;
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVersioned } from "./IVersioned.sol";
import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";
/**
* @dev this is the common interface for upgradeable contracts
*/
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
/**
* @dev an interface for a versioned contract
*/
interface IVersioned {
function version() external view returns (uint16);
}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IExternalProtectionVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IVault } from "./IVault.sol";
interface IMasterVault is IVault {}
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;
import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";
import { Token } from "../../token/Token.sol";
// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");
interface IVault is IUpgradeable {
/**
* @dev triggered when tokens have been withdrawn from the vault
*/
event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);
/**
* @dev triggered when tokens have been burned from the vault
*/
event FundsBurned(Token indexed token, address indexed caller, uint256 amount);
/**
* @dev tells whether the vault accepts native token deposits
*/
function isPayable() external view returns (bool);
/**
* @dev withdraws funds held by the contract and sends them to an account
*/
function withdrawFunds(
Token token,
address payable target,
uint256 amount
) external;
/**
* @dev burns funds held by the contract
*/
function burn(Token token, uint256 amount) external;
} | * @dev triggered when the default trading fee is updated/ | event DefaultTradingFeePPMUpdated(uint32 prevFeePPM, uint32 newFeePPM);
| 10,394,312 | [
1,
10668,
329,
1347,
326,
805,
1284,
7459,
14036,
353,
3526,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
2989,
1609,
7459,
14667,
6584,
49,
7381,
12,
11890,
1578,
2807,
14667,
6584,
49,
16,
2254,
1578,
394,
14667,
6584,
49,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
interface IOwnable {
function policy() external view returns (address);
function renounceManagement() external;
function pushManagement(address newOwner_) external;
function pullManagement() external;
}
contract Ownable is IOwnable {
event OwnershipPushed(address indexed previousOwner, address indexed newOwner);
event OwnershipPulled(address indexed previousOwner, address indexed newOwner);
address internal _owner;
address internal _newOwner;
constructor() {
_owner = msg.sender;
emit OwnershipPushed(address(0), _owner);
}
function policy() public view override returns (address) {
return _owner;
}
modifier onlyPolicy {
require(_owner == msg.sender, "Ownable: caller is not the owner" );
_;
}
function renounceManagement() public virtual override onlyPolicy() {
emit OwnershipPushed(_owner, address(0));
_owner = address(0);
}
function pushManagement(address newOwner_) public virtual override onlyPolicy() {
require(newOwner_ != address(0), "Ownable: new owner is the zero address");
emit OwnershipPushed(_owner, newOwner_);
_newOwner = newOwner_;
}
function pullManagement() public virtual override {
require(msg.sender == _newOwner, "Ownable: must be new owner to pull");
emit OwnershipPulled(_owner, _newOwner);
_owner = _newOwner;
}
}
interface IERC2612Permit {
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
function nonces(address owner) external view returns (uint256);
}
abstract contract ERC20Permit is ERC20, IERC2612Permit {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
constructor() {
uint256 chainID;
assembly {
chainID := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name())),
keccak256(bytes("1")), // Version
chainID,
address(this)
)
);
}
function permit(
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "Permit: expired deadline");
bytes32 hashStruct =
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline));
bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct));
address signer = ecrecover(_hash, v, r, s);
require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
}
library FullMath {
function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, ~uint256(0));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & ~d;
d /= pow2;
l /= pow2;
l += h * ((~pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
require(h < d, 'FullMath::mulDiv: overflow');
return fullDiv(l, h, d);
}
}
library FixedPoint {
struct uq112x112 {
uint224 _x;
}
struct uq144x112 {
uint256 _x;
}
uint8 private constant RESOLUTION = 112;
uint256 private constant Q112 = 0x10000000000000000000000000000;
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000;
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
function decode112with18(uq112x112 memory self) internal pure returns (uint) {
return uint(self._x) / 5192296858534827;
}
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= ~uint144(0)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= ~uint224(0), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= ~uint224(0), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
}
interface ITreasury {
function deposit( uint _amount, address _token, uint _profit ) external;
function valueOf( address _token, uint _amount ) external view returns ( uint value_ );
}
interface IBondCalculator {
function valuation( address _LP, uint _amount ) external view returns ( uint );
function markdown( address _LP ) external view returns ( uint );
}
interface IStaking {
function stake( uint _amount, address _recipient ) external returns ( bool );
}
interface IStakingHelper {
function stake( uint _amount, address _recipient ) external;
}
contract OlympusBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
/* ======== EVENTS ======== */
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( uint indexed payout, uint indexed remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
/* ======== STATE VARIABLES ======== */
address public immutable OHM; // token given as payment for bond
address public immutable principle; // token used to create bond, DAI, FRAX etc.
address public immutable treasury; // mints OHM when receives principle
address public immutable DAO; // receives profit share from bond
bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different
address public immutable bondCalculator; // calculates value of LP tokens
address public staking; // to auto-stake payout
address public stakingHelper; // to stake and claim if no staking warmup
bool public useHelper;
Terms public terms; // stores terms for new bonds
Adjust public adjustment; // stores adjustment to BCV data
uint public totalDebt; // total value of outstanding bonds; used for pricing
uint public lastDecay; // reference block for debt decay
/* ======== STRUCTS ======== */
// Info for creating new bonds
struct Terms {
uint controlVariable; // scaling variable for price
uint vestingTerm; // in blocks
uint minimumPrice; // vs principle value
uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5%
uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid)
uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt
}
struct Bond {
uint valueRemaining; // value of principle given
uint payoutRemaining; // OHM remaining to be paid
uint vestingPeriod; // Blocks left to vest
uint lastBlock; // Last interaction
uint pricePaid; // In DAI, for front end viewing
}
mapping(address => Bond) public bondInfo; // Stores bond information for depositor
// Info for incremental adjustments to control variable
struct Adjust {
bool add; // addition or subtraction
uint rate; // increment
uint target; // BCV when adjustment finished
uint buffer; // minimum length (in blocks) between adjustments
uint lastBlock; // block when last adjustment made
}
/* ======== INITIALIZATION ======== */
constructor (
address _OHM,
address _principle,
address _treasury,
address _DAO,
address _bondCalculator
) {
require(_OHM != address(0));
OHM = _OHM;
require(_principle != address(0));
principle = _principle;
require(_treasury != address(0));
treasury = _treasury;
require(_DAO != address(0));
DAO = _DAO;
// bondCalculator should be address(0) if not LP bond
bondCalculator = _bondCalculator;
isLiquidityBond = (_bondCalculator != address(0));
}
/**
* @notice initializes bond parameters
* @param _controlVariable uint
* @param _vestingTerm uint
* @param _minimumPrice uint
* @param _maxPayout uint
* @param _fee uint
* @param _maxDebt uint
* @param _initialDebt uint
*/
function initializeBondTerms(
uint _controlVariable,
uint _vestingTerm,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt
) external onlyPolicy() {
require(terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms({
controlVariable: _controlVariable,
vestingTerm: _vestingTerm,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt
});
totalDebt = _initialDebt;
lastDecay = block.number;
}
/* ======== POLICY FUNCTIONS ======== */
enum PARAMETER {VESTING, PAYOUT, FEE, DEBT}
/**
* @notice set parameters for new bonds
* @param _parameter PARAMETER
* @param _input uint
*/
function setBondTerms(PARAMETER _parameter, uint _input) external onlyPolicy() {
if (_parameter == PARAMETER.VESTING) { // 0
require(_input >= 10000, "Vesting must be longer than 36 hours");
terms.vestingTerm = _input;
} else if (_parameter == PARAMETER.PAYOUT) { // 1
require(_input <= 1000, "Payout cannot be above 1 percent");
terms.maxPayout = _input;
} else if (_parameter == PARAMETER.FEE) { // 2
require(_input <= 10000, "DAO fee cannot exceed payout");
terms.fee = _input;
} else if (_parameter == PARAMETER.DEBT) { // 3
terms.maxDebt = _input;
}
}
/**
* @notice set control variable adjustment
* @param _addition bool
* @param _increment uint
* @param _target uint
* @param _buffer uint
*/
function setAdjustment (
bool _addition,
uint _increment,
uint _target,
uint _buffer
) external onlyPolicy() {
require(_increment <= terms.controlVariable * 25 / 1000, "Increment too large");
adjustment = Adjust({
add: _addition,
rate: _increment,
target: _target,
buffer: _buffer,
lastBlock: block.number
});
}
/**
* @notice set contract for auto stake
* @param _staking address
* @param _helper bool
*/
function setStaking(address _staking, bool _helper) external onlyPolicy() {
require(_staking != address(0));
if (_helper) {
useHelper = true;
stakingHelper = _staking;
} else {
useHelper = false;
staking = _staking;
}
}
/* ======== USER FUNCTIONS ======== */
/**
* @notice deposit bond
* @param _amount uint
* @param _maxPrice uint
* @param _depositor address
* @return uint
*/
function deposit(
uint _amount,
uint _maxPrice,
address _depositor
) external returns (uint) {
require(_depositor != address(0), "Invalid address");
decayDebt();
require(totalDebt <= terms.maxDebt, "Max capacity reached");
uint priceInUSD = bondPriceInUSD(); // Stored in bond info
uint nativePrice = _bondPrice();
require(_maxPrice >= nativePrice, "Slippage limit: more than max price"); // slippage protection
uint value;
if (isLiquidityBond) { // LP is calculated at risk-free value
value = IBondCalculator(bondCalculator).valuation(principle, _amount);
} else { // reserve is converted to OHM decimals
value = _amount * 10**IERC20Metadata(OHM).decimals() / 10**IERC20Metadata(principle).decimals();
}
uint payout = payoutFor(value); // payout to bonder is computed
require(payout >= 10000000, "Bond too small"); // must be > 0.01 OHM ( underflow protection )
require(payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage
// profits are calculated
uint fee = payout * terms.fee / 10000;
uint profit = value - payout - fee;
/**
principle is transferred in approved and
deposited into the treasury, returning (_amount - profit) OHM
*/
// IERC20(principle).safeTransferFrom(msg.sender, address(this), _amount);
// IERC20(principle).approve(address(treasury), _amount);
// ITreasury(treasury).deposit(_amount, principle, profit);
IERC20(principle).safeTransferFrom(msg.sender, treasury, _amount);
// IERC20(principle).approve(address(treasury), _amount);
ITreasury(treasury).deposit(_amount, principle, profit);
IERC20(OHM).safeTransfer(DAO, fee);
// total debt is increased
totalDebt = totalDebt + value;
// depositor info is stored
Bond memory info = bondInfo[_depositor];
bondInfo[_depositor] = Bond({
valueRemaining: info.valueRemaining + value, // add on to previous
payoutRemaining: info.payoutRemaining + payout, // amounts if they exist
vestingPeriod: terms.vestingTerm,
lastBlock: block.number,
pricePaid: priceInUSD
});
// indexed events are emitted
emit BondCreated(_amount, payout, block.number + terms.vestingTerm, priceInUSD);
emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio());
adjust(); // control variable is adjusted
return payout;
}
/**
@notice redeem all unvested bonds
@param _stake bool
@return payout_ uint
*/
function redeem(bool _stake) external returns (uint) {
Bond memory info = bondInfo[msg.sender];
uint percentVested = percentVestedFor(msg.sender); // (blocks since last interaction / vesting term remaining)
if (percentVested >= 10000) { // if fully vested
delete bondInfo[msg.sender]; // delete user info
totalDebt -= info.valueRemaining; // reduce debt
// emit BondRedeemed(info.payoutRemaining, 0); // emit bond data
return stakeOrSend(_stake, info.payoutRemaining); // pay user everything due
} else { // if unfinished
// calculate payout vested
uint value = info.valueRemaining * percentVested / 10000;
uint payout = info.payoutRemaining * percentVested / 10000;
uint blocksSinceLast = block.number - info.lastBlock;
// store updated deposit info
bondInfo[msg.sender] = Bond({
valueRemaining: info.valueRemaining - value,
payoutRemaining: info.payoutRemaining - payout,
vestingPeriod: info.vestingPeriod - blocksSinceLast,
lastBlock: block.number,
pricePaid: info.pricePaid
});
// reduce total debt by vested amount
totalDebt -= value;
emit BondRedeemed(payout, bondInfo[msg.sender].payoutRemaining);
return stakeOrSend(_stake, payout);
}
}
/* ======== INTERNAL HELPER FUNCTIONS ======== */
/**
@notice allow user to stake payout automatically
@param _stake bool
@param _amount uint
@return uint
*/
function stakeOrSend(bool _stake, uint _amount) internal returns (uint) {
emit BondPriceChanged(bondPriceInUSD(), _bondPrice(), debtRatio());
if (!_stake ) { // if user does not want to stake
IERC20(OHM).transfer(msg.sender, _amount); // send payout
} else { // if user wants to stake
IERC20(OHM).approve(staking, _amount);
IStaking(staking).stake(_amount, msg.sender); // stake payout
}
return _amount;
}
/**
* @notice makes incremental adjustment to control variable
*/
function adjust() internal {
uint blockCanAdjust = adjustment.lastBlock + adjustment.buffer;
if (adjustment.rate != 0 && block.number >= blockCanAdjust) {
uint initial = terms.controlVariable;
if (adjustment.add) {
terms.controlVariable = terms.controlVariable + adjustment.rate;
if (terms.controlVariable >= adjustment.target) {
adjustment.rate = 0;
}
} else {
terms.controlVariable = terms.controlVariable - adjustment.rate;
if (terms.controlVariable <= adjustment.target) {
adjustment.rate = 0;
}
}
adjustment.lastBlock = block.number;
emit ControlVariableAdjustment(initial, terms.controlVariable, adjustment.rate, adjustment.add);
}
}
/**
* @notice reduce total debt
*/
function decayDebt() internal {
totalDebt = totalDebt - debtDecay();
lastDecay = block.number;
}
/* ======== VIEW FUNCTIONS ======== */
/**
* @notice determine maximum bond size
* @return uint
*/
function maxPayout() public view returns (uint) {
return IERC20(OHM).totalSupply() * terms.maxPayout / 100000;
}
/**
* @notice calculate interest due for new bond
* @param _value uint
* @return uint
*/
function payoutFor(uint _value) public view returns (uint) {
return FixedPoint.fraction(_value, bondPrice()).decode112with18() / 1e16;
}
/**
* @notice calculate current bond premium
* @return price_ uint
*/
function bondPrice() public view returns (uint price_) {
price_ = (terms.controlVariable * debtRatio() + 1000000000) / 1e7;
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
}
}
/**
* @notice calculate current bond price and remove floor if above
* @return price_ uint
*/
function _bondPrice() internal returns (uint price_) {
price_ = (terms.controlVariable * debtRatio() + 1000000000)/1e7;
if (price_ < terms.minimumPrice) {
price_ = terms.minimumPrice;
} else if (terms.minimumPrice != 0) {
terms.minimumPrice = 0;
}
}
/**
* @notice converts bond price to DAI value
* @return price_ uint
*/
function bondPriceInUSD() public view returns (uint price_) {
if (isLiquidityBond) {
price_ = bondPrice() * IBondCalculator(bondCalculator).markdown(principle) / 100;
} else {
price_ = bondPrice() * 10**IERC20Metadata(principle).decimals() / 100;
}
}
/**
* @notice calculate current ratio of debt to OHM supply
* @return debtRatio_ uint
*/
function debtRatio() public view returns (uint debtRatio_) {
uint supply = IERC20(OHM).totalSupply();
debtRatio_ = FixedPoint.fraction(currentDebt() * 1e9, supply).decode112with18() / 1e18;
}
/**
* @notice debt ratio in same terms for reserve or liquidity bonds
* @return uint
*/
function standardizedDebtRatio() external view returns (uint) {
if (isLiquidityBond) {
return debtRatio() * (IBondCalculator(bondCalculator).markdown(principle)) / 1e9;
} else {
return debtRatio();
}
}
/**
* @notice calculate debt factoring in decay
* @return uint
*/
function currentDebt() public view returns (uint) {
return totalDebt - debtDecay();
}
/**
* @notice amount to decay total debt by
* @return decay_ uint
*/
function debtDecay() public view returns (uint decay_) {
uint blocksSinceLast = block.number - lastDecay;
decay_ = totalDebt * blocksSinceLast / terms.vestingTerm;
if (decay_ > totalDebt) {
decay_ = totalDebt;
}
}
/**
@notice calculate how far into vesting a depositor is
@param _depositor address
@return percentVested_ uint
*/
function percentVestedFor(address _depositor) public view returns (uint percentVested_) {
Bond memory bond = bondInfo[_depositor];
uint blocksSinceLast = block.number - bond.lastBlock;
uint vestingPeriod = bond.vestingPeriod;
if (vestingPeriod > 0) {
percentVested_ = blocksSinceLast * 10000 / vestingPeriod;
} else {
percentVested_ = 0;
}
}
/**
@notice calculate amount of OHM available for claim by depositor
@param _depositor address
@return pendingPayout_ uint
*/
function pendingPayoutFor(address _depositor) external view returns (uint pendingPayout_) {
uint percentVested = percentVestedFor(_depositor);
uint payoutRemaining = bondInfo[_depositor].payoutRemaining;
if (percentVested >= 10000) {
pendingPayout_ = payoutRemaining;
} else {
pendingPayout_ = payoutRemaining * percentVested / 10000;
}
}
/* ======= AUXILLIARY ======= */
/**
* @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO
* @return bool
*/
function recoverLostToken(address _token) external returns (bool) {
require(_token != OHM);
require(_token != principle);
IERC20(_token).safeTransfer(DAO, IERC20(_token).balanceOf(address(this)));
return true;
}
}
| LP is calculated at risk-free value
| if (isLiquidityBond) { | 1,040,892 | [
1,
14461,
353,
8894,
622,
18404,
17,
9156,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
309,
261,
291,
48,
18988,
24237,
9807,
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,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x8CC23A8CFE803f8E9Ee978bD7F9D343eeA0Cf82F/sources/src/LockRewards.sol | * @notice Implements internal getAccount logic @param owner: address to check informations/ | function _getAccount(address owner)
internal
view
returns (uint256 balance, uint256 lockEpochs, uint256 lastEpochPaid, uint256[] memory rewards)
{
rewards = new uint256[](rewardTokens.length);
for (uint256 i = 0; i < accounts[owner].rewardTokens.length;) {
address addr = accounts[owner].rewardTokens[i];
rewards[i] = accounts[owner].rewards[addr];
unchecked {
++i;
}
}
return (accounts[owner].balance, accounts[owner].lockEpochs, accounts[owner].lastEpochPaid, rewards);
}
| 9,625,246 | [
1,
17516,
2713,
23393,
4058,
282,
3410,
30,
1758,
358,
866,
26978,
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,
389,
588,
3032,
12,
2867,
3410,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
11013,
16,
2254,
5034,
2176,
14638,
87,
16,
2254,
5034,
1142,
14638,
16507,
350,
16,
2254,
5034,
8526,
3778,
283,
6397,
13,
203,
565,
288,
203,
3639,
283,
6397,
273,
394,
2254,
5034,
8526,
12,
266,
2913,
5157,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
9484,
63,
8443,
8009,
266,
2913,
5157,
18,
2469,
30943,
288,
203,
5411,
1758,
3091,
273,
9484,
63,
8443,
8009,
266,
2913,
5157,
63,
77,
15533,
203,
5411,
283,
6397,
63,
77,
65,
273,
9484,
63,
8443,
8009,
266,
6397,
63,
4793,
15533,
203,
203,
5411,
22893,
288,
203,
7734,
965,
77,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
327,
261,
13739,
63,
8443,
8009,
12296,
16,
9484,
63,
8443,
8009,
739,
14638,
87,
16,
9484,
63,
8443,
8009,
2722,
14638,
16507,
350,
16,
283,
6397,
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
] |
./full_match/5/0x9d45d05494eD6E8964a3818E506C8488a4FEBb82/sources/Users/seb/repo/hunt/neverlose/contract/contracts/WRNRewardPool.sol | 8.8M blocks (appx 3 years and 7 months)
| REWARD_END_BLOCK = REWARD_START_BLOCK.add(rewardBlocks); | 1,953,354 | [
1,
28,
18,
28,
49,
4398,
261,
2910,
92,
890,
11387,
471,
2371,
8846,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2438,
21343,
67,
4415,
67,
11403,
273,
2438,
21343,
67,
7570,
67,
11403,
18,
1289,
12,
266,
2913,
6450,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/80001/0x8D506fbAb52d3982f32d23E3A8c987F83ae4E792/sources/contracts/ccip/KreepyKrittersPortal.sol | * @notice Notify cross chain portal instance on `destinationChainSelector` that tokens were burned on this chain. Payment for CCIP service is payed in link stored in this contract. Only callable by BurnOperators. @dev After validation that the given tokenIds are burned on this chain, they will be burned on the destination chain too. @param destinationChainSelector CCIP chain selector for destination chain. @param data Encoded brun data of sender and tokenIds, can be obtained via {KreepyKrittersPortalEncoder-encodeBurn}. @param extraArgs CCIP extraArgs, encoding gasLimit on destination chain and possibly future protocol options./ | function notifyBurned(
uint64 destinationChainSelector,
bytes memory data,
bytes calldata extraArgs
) external onlyBurnOperator whenNotPaused {
address target = crossChainTarget[destinationChainSelector];
if (target == address(0)) {
revert InvalidDestinationChainSelector(destinationChainSelector);
}
uint256 command = data.readUInt8(OFFSET_COMMAND);
if (command != COMMAND_BURN)
revert InvalidCommandEncoding(command, COMMAND_BURN);
address sender = data.readAddress(OFFSET_SENDER);
if (sender != msg.sender)
revert InvalidSenderEncoding(sender, msg.sender);
uint256 length = (data.length - OFFSET_BURN_TOKENIDS) / SIZE_TOKENID;
uint256 tokenId;
for (uint256 i = 0; i < length; ) {
unchecked {
tokenId = data.readUInt16(
OFFSET_BURN_TOKENIDS + i * SIZE_TOKENID
);
}
if (!_isBurned(tokenId)) revert NotBurned(tokenId);
unchecked {
++i;
}
}
_notifyBurned(destinationChainSelector, target, data, extraArgs);
}
| 8,812,480 | [
1,
9168,
6828,
2687,
11899,
791,
603,
1375,
10590,
3893,
4320,
68,
716,
2430,
4591,
18305,
329,
603,
333,
2687,
18,
12022,
364,
16525,
2579,
1156,
353,
8843,
329,
316,
1692,
4041,
316,
333,
6835,
18,
5098,
4140,
635,
605,
321,
24473,
18,
225,
7360,
3379,
716,
326,
864,
1147,
2673,
854,
18305,
329,
603,
333,
2687,
16,
2898,
903,
506,
18305,
329,
603,
326,
2929,
2687,
4885,
18,
225,
2929,
3893,
4320,
16525,
2579,
2687,
3451,
364,
2929,
2687,
18,
225,
501,
23306,
324,
2681,
501,
434,
5793,
471,
1147,
2673,
16,
848,
506,
12700,
3970,
288,
47,
266,
881,
93,
47,
583,
5432,
24395,
7204,
17,
3015,
38,
321,
5496,
225,
2870,
2615,
16525,
2579,
2870,
2615,
16,
2688,
16189,
3039,
603,
2929,
2687,
471,
10016,
3563,
1771,
702,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5066,
38,
321,
329,
12,
203,
3639,
2254,
1105,
2929,
3893,
4320,
16,
203,
3639,
1731,
3778,
501,
16,
203,
3639,
1731,
745,
892,
2870,
2615,
203,
565,
262,
3903,
1338,
38,
321,
5592,
1347,
1248,
28590,
288,
203,
3639,
1758,
1018,
273,
6828,
3893,
2326,
63,
10590,
3893,
4320,
15533,
203,
3639,
309,
261,
3299,
422,
1758,
12,
20,
3719,
288,
203,
5411,
15226,
1962,
5683,
3893,
4320,
12,
10590,
3893,
4320,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1296,
273,
501,
18,
896,
14342,
28,
12,
11271,
67,
19104,
1769,
203,
3639,
309,
261,
3076,
480,
17266,
67,
38,
8521,
13,
203,
5411,
15226,
1962,
2189,
4705,
12,
3076,
16,
17266,
67,
38,
8521,
1769,
203,
203,
3639,
1758,
5793,
273,
501,
18,
896,
1887,
12,
11271,
67,
1090,
18556,
1769,
203,
3639,
309,
261,
15330,
480,
1234,
18,
15330,
13,
203,
5411,
15226,
1962,
12021,
4705,
12,
15330,
16,
1234,
18,
15330,
1769,
203,
203,
3639,
2254,
5034,
769,
273,
261,
892,
18,
2469,
300,
26019,
67,
38,
8521,
67,
8412,
19516,
13,
342,
11963,
67,
8412,
734,
31,
203,
3639,
2254,
5034,
1147,
548,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
262,
288,
203,
5411,
22893,
288,
203,
7734,
1147,
548,
273,
501,
18,
896,
14342,
2313,
12,
203,
10792,
26019,
67,
38,
8521,
67,
8412,
19516,
397,
277,
380,
11963,
67,
8412,
734,
203,
7734,
11272,
203,
5411,
289,
203,
5411,
309,
16051,
67,
291,
38,
321,
2
] |
// Ethertote - Official Token Sale Contract
// 28.07.18
//
// Any unsold tokens can be sent directly to the TokenBurn Contract
// by anyone once the Token Sale is complete -
// this is a PUBLIC function that anyone can call!!
//
// All Eth raised during the token sale is automatically sent to the
// EthRaised smart contract for distribution
pragma solidity ^0.4.24;
///////////////////////////////////////////////////////////////////////////////
// SafeMath Library
///////////////////////////////////////////////////////////////////////////////
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// ----------------------------------------------------------------------------
// Imported Token Contract functions
// ----------------------------------------------------------------------------
contract EthertoteToken {
function thisContractAddress() public pure returns (address) {}
function balanceOf(address) public pure returns (uint256) {}
function transfer(address, uint) public {}
}
// ----------------------------------------------------------------------------
// Main Contract
// ----------------------------------------------------------------------------
contract TokenSale {
using SafeMath for uint256;
EthertoteToken public token;
address public admin;
address public thisContractAddress;
// address of the TOTE token original smart contract
address public tokenContractAddress = 0x42be9831FFF77972c1D0E1eC0aA9bdb3CaA04D47;
// address of TokenBurn contract to "burn" unsold tokens
// for further details, review the TokenBurn contract and verify code on Etherscan
address public tokenBurnAddress = 0xadCa18DC9489C5FE5BdDf1A8a8C2623B66029198;
// address of EthRaised contract, that will be used to distribute funds
// raised by the token sale. Added as "wallet address"
address public ethRaisedAddress = 0x9F73D808807c71Af185FEA0c1cE205002c74123C;
uint public preIcoPhaseCountdown; // used for website tokensale
uint public icoPhaseCountdown; // used for website tokensale
uint public postIcoPhaseCountdown; // used for website tokensale
// pause token sale in an emergency [true/false]
bool public tokenSaleIsPaused;
// note the pause time to allow special function to extend closingTime
uint public tokenSalePausedTime;
// note the resume time
uint public tokenSaleResumedTime;
// The time (in seconds) that needs to be added on to the closing time
// in the event of an emergency pause of the token sale
uint public tokenSalePausedDuration;
// Amount of wei raised
uint256 public weiRaised;
// 1000 tokens per Eth - 9,000,000 tokens for sale
uint public maxEthRaised = 9000;
// Maximum amount of Wei that can be raised
// e.g. 9,000,000 tokens for sale with 1000 tokens per 1 eth
// means maximum Wei raised would be maxEthRaised * 1000000000000000000
uint public maxWeiRaised = maxEthRaised.mul(1000000000000000000);
// starting time and closing time of Crowdsale
// scheduled start on Monday, August 27th 2018 at 5:00pm GMT+1
uint public openingTime = 1535385600;
uint public closingTime = openingTime.add(7 days);
// used as a divider so that 1 eth will buy 1000 tokens
// set rate to 1,000,000,000,000,000
uint public rate = 1000000000000000;
// minimum and maximum spend of eth per transaction
uint public minSpend = 100000000000000000; // 0.1 Eth
uint public maxSpend = 100000000000000000000; // 100 Eth
// MODIFIERS
modifier onlyAdmin {
require(msg.sender == admin
);
_;
}
// EVENTS
event Deployed(string, uint);
event SalePaused(string, uint);
event SaleResumed(string, uint);
event TokensBurned(string, uint);
// ---------------------------------------------------------------------------
// Constructor function
// _ethRaisedContract = Address where collected funds will be forwarded to
// _tokenContractAddress = Address of the original token contract being sold
// ---------------------------------------------------------------------------
constructor() public {
admin = msg.sender;
thisContractAddress = address(this);
token = EthertoteToken(tokenContractAddress);
require(ethRaisedAddress != address(0));
require(tokenContractAddress != address(0));
require(tokenBurnAddress != address(0));
preIcoPhaseCountdown = openingTime;
icoPhaseCountdown = closingTime;
// after 14 days the "post-tokensale" header section of the homepage
// on the website will be removed based on this time
postIcoPhaseCountdown = closingTime.add(14 days);
emit Deployed("Ethertote Token Sale contract deployed", now);
}
// check balance of this smart contract
function tokenSaleTokenBalance() public view returns(uint) {
return token.balanceOf(thisContractAddress);
}
// check the token balance of any ethereum address
function getAnyAddressTokenBalance(address _address) public view returns(uint) {
return token.balanceOf(_address);
}
// confirm if The Token Sale has finished
function tokenSaleHasFinished() public view returns (bool) {
return now > closingTime;
}
// this function will send any unsold tokens to the null TokenBurn contract address
// once the crowdsale is finished, anyone can publicly call this function!
function burnUnsoldTokens() public {
require(tokenSaleIsPaused == false);
require(tokenSaleHasFinished() == true);
token.transfer(tokenBurnAddress, tokenSaleTokenBalance());
emit TokensBurned("tokens sent to TokenBurn contract", now);
}
// function to temporarily pause token sale if needed
function pauseTokenSale() onlyAdmin public {
// confirm the token sale hasn't already completed
require(tokenSaleHasFinished() == false);
// confirm the token sale isn't already paused
require(tokenSaleIsPaused == false);
// pause the sale and note the time of the pause
tokenSaleIsPaused = true;
tokenSalePausedTime = now;
emit SalePaused("token sale has been paused", now);
}
// function to resume token sale
function resumeTokenSale() onlyAdmin public {
// confirm the token sale is currently paused
require(tokenSaleIsPaused == true);
tokenSaleResumedTime = now;
// now calculate the difference in time between the pause time
// and the resume time, to establish how long the sale was
// paused for. This time now needs to be added to the closingTime.
// Note: if the token sale was paused whilst the sale was live and was
// paused before the sale ended, then the value of tokenSalePausedTime
// will always be less than the value of tokenSaleResumedTime
tokenSalePausedDuration = tokenSaleResumedTime.sub(tokenSalePausedTime);
// add the total pause time to the closing time.
closingTime = closingTime.add(tokenSalePausedDuration);
// extend post ICO countdown for the web-site
postIcoPhaseCountdown = closingTime.add(14 days);
// now resume the token sale
tokenSaleIsPaused = false;
emit SaleResumed("token sale has now resumed", now);
}
// ----------------------------------------------------------------------------
// Event for token purchase logging
// purchaser = the contract address that paid for the tokens
// beneficiary = the address who got the tokens
// value = the amount (in Wei) paid for purchase
// amount = the amount of tokens purchased
// ----------------------------------------------------------------------------
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
// ----------------------------------------------------------------------------
// fallback function ***DO NOT OVERRIDE***
// allows purchase of tokens directly from MEW and other wallets
// will conform to require statements set out in buyTokens() function
// ----------------------------------------------------------------------------
function () external payable {
buyTokens(msg.sender);
}
// ----------------------------------------------------------------------------
// function for front-end token purchase on our website ***DO NOT OVERRIDE***
// buyer = Address of the wallet performing the token purchase
// ----------------------------------------------------------------------------
function buyTokens(address buyer) public payable {
// check Crowdsale is open (can disable for testing)
require(openingTime <= block.timestamp);
require(block.timestamp < closingTime);
// minimum purchase of 100 tokens (0.1 eth)
require(msg.value >= minSpend);
// maximum purchase per transaction to allow broader
// token distribution during tokensale
require(msg.value <= maxSpend);
// stop sales of tokens if token balance is 0
require(tokenSaleTokenBalance() > 0);
// stop sales of tokens if Token sale is paused
require(tokenSaleIsPaused == false);
// log the amount being sent
uint256 weiAmount = msg.value;
preValidatePurchase(buyer, weiAmount);
// calculate token amount to be sold
uint256 tokens = getTokenAmount(weiAmount);
// check that the amount of eth being sent by the buyer
// does not exceed the equivalent number of tokens remaining
require(tokens <= tokenSaleTokenBalance());
// update state
weiRaised = weiRaised.add(weiAmount);
processPurchase(buyer, tokens);
emit TokenPurchase(
msg.sender,
buyer,
weiAmount,
tokens
);
updatePurchasingState(buyer, weiAmount);
forwardFunds();
postValidatePurchase(buyer, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
// ----------------------------------------------------------------------------
// Validation of an incoming purchase
// ----------------------------------------------------------------------------
function preValidatePurchase(
address buyer,
uint256 weiAmount
)
internal pure
{
require(buyer != address(0));
require(weiAmount != 0);
}
// ----------------------------------------------------------------------------
// Validation of an executed purchase
// ----------------------------------------------------------------------------
function postValidatePurchase(
address,
uint256
)
internal pure
{
// optional override
}
// ----------------------------------------------------------------------------
// Source of tokens
// ----------------------------------------------------------------------------
function deliverTokens(
address buyer,
uint256 tokenAmount
)
internal
{
token.transfer(buyer, tokenAmount);
}
// ----------------------------------------------------------------------------
// The following function is executed when a purchase has been validated
// and is ready to be executed
// ----------------------------------------------------------------------------
function processPurchase(
address buyer,
uint256 tokenAmount
)
internal
{
deliverTokens(buyer, tokenAmount);
}
// ----------------------------------------------------------------------------
// Override for extensions that require an internal state to check for
// validity (current user contributions, etc.)
// ----------------------------------------------------------------------------
function updatePurchasingState(
address,
uint256
)
internal pure
{
// optional override
}
// ----------------------------------------------------------------------------
// Override to extend the way in which ether is converted to tokens.
// _weiAmount Value in wei to be converted into tokens
// return Number of tokens that can be purchased with the specified _weiAmount
// ----------------------------------------------------------------------------
function getTokenAmount(uint256 weiAmount)
internal view returns (uint256)
{
return weiAmount.div(rate);
}
// ----------------------------------------------------------------------------
// how ETH is stored/forwarded on purchases.
// Sent to the EthRaised Contract
// ----------------------------------------------------------------------------
function forwardFunds() internal {
ethRaisedAddress.transfer(msg.value);
}
// functions for tokensale information on the website
function maximumRaised() public view returns(uint) {
return maxWeiRaised;
}
function amountRaised() public view returns(uint) {
return weiRaised;
}
function timeComplete() public view returns(uint) {
return closingTime;
}
// special function to delay the token sale if necessary
function delayOpeningTime(uint256 _openingTime) onlyAdmin public {
openingTime = _openingTime;
closingTime = openingTime.add(7 days);
preIcoPhaseCountdown = openingTime;
icoPhaseCountdown = closingTime;
postIcoPhaseCountdown = closingTime.add(14 days);
}
} | this function will send any unsold tokens to the null TokenBurn contract address once the crowdsale is finished, anyone can publicly call this function! | function burnUnsoldTokens() public {
require(tokenSaleIsPaused == false);
require(tokenSaleHasFinished() == true);
token.transfer(tokenBurnAddress, tokenSaleTokenBalance());
emit TokensBurned("tokens sent to TokenBurn contract", now);
}
| 2,551,258 | [
1,
2211,
445,
903,
1366,
1281,
16804,
1673,
2430,
358,
326,
446,
3155,
38,
321,
6835,
1758,
3647,
326,
276,
492,
2377,
5349,
353,
6708,
16,
1281,
476,
848,
1071,
715,
745,
333,
445,
5,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
18305,
984,
87,
1673,
5157,
1435,
1071,
288,
203,
1377,
2583,
12,
2316,
30746,
2520,
28590,
422,
629,
1769,
203,
1377,
2583,
12,
2316,
30746,
5582,
10577,
1435,
422,
638,
1769,
203,
1377,
1147,
18,
13866,
12,
2316,
38,
321,
1887,
16,
1147,
30746,
1345,
13937,
10663,
203,
1377,
3626,
13899,
38,
321,
329,
2932,
7860,
3271,
358,
3155,
38,
321,
6835,
3113,
2037,
1769,
203,
225,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x705A5Aaa40E2D7C2489C86e5d3FA2214F4e7d430/sources/contracts/Staking2.sol | VARIABLES & CONSTANTS 1. Tokens | contract MaskedFarming {
using SafeMath for uint;
address _burnVault;
address public _owner;
MaskedInterface public token;
IUniswapV2Pair public lpToken;
uint public POOL_MULTIPLIER_UPDATED;
uint public POOL_lastRewardBlock;
uint public immutable POOL_START;
uint public constant POOL_START_DELAY = 1;
uint public constant PRECISION = 1e5;
address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IUniswapV2Pair constant ETH_USDC_PAIR = IUniswapV2Pair(0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc);
struct User {
uint POOL_provided;
uint POOL_rewardDebt;
}
mapping(address => User) public users;
constructor(address owner, address burnVault){
POOL_MULTIPLIER = uint(7500 * 1e18) / POOL_MULTIPLIER_UPDATE_1WEEK;
POOL_MULTIPLIER_UPDATED = block.number.add(POOL_START_DELAY);
POOL_START = block.number.add(POOL_START_DELAY);
_owner = owner;
_burnVault = burnVault;
}
modifier onlyOwner(){
require(msg.sender == _owner);
_;
}
function setOwnerAddress(address _gov) external onlyOwner{
_owner = _gov;
}
function setTokenAddress(address _token) external onlyOwner{
token = MaskedInterface(_token);
}
function setLPAddress(address _lp) external onlyOwner{
lpToken = IUniswapV2Pair(_lp);
}
function CalculateReward(uint _from, uint _to) private view returns (uint){
uint blocks;
if(_from >= POOL_START && _to >= POOL_START){
blocks = _to.sub(_from);
}
return blocks.mul(POOL_MULTIPLIER);
}
function CalculateReward(uint _from, uint _to) private view returns (uint){
uint blocks;
if(_from >= POOL_START && _to >= POOL_START){
blocks = _to.sub(_from);
}
return blocks.mul(POOL_MULTIPLIER);
}
function POOL_update() private {
uint lpSupply = lpToken.balanceOf(address(this));
if (POOL_lastRewardBlock == 0 || lpSupply == 0) {
POOL_lastRewardBlock = block.number;
return;
}
uint reward = CalculateReward(POOL_lastRewardBlock, block.number);
POOL_accTokensPerLP = POOL_accTokensPerLP.add(
reward.mul(1e18).div(lpSupply)
);
POOL_lastRewardBlock = block.number;
if(block.number >= POOL_MULTIPLIER_UPDATED.add(POOL_MULTIPLIER_UPDATE_1WEEK)){
POOL_MULTIPLIER = POOL_MULTIPLIER.mul(3).div(4);
POOL_MULTIPLIER_UPDATED = block.number;
}
}
function POOL_update() private {
uint lpSupply = lpToken.balanceOf(address(this));
if (POOL_lastRewardBlock == 0 || lpSupply == 0) {
POOL_lastRewardBlock = block.number;
return;
}
uint reward = CalculateReward(POOL_lastRewardBlock, block.number);
POOL_accTokensPerLP = POOL_accTokensPerLP.add(
reward.mul(1e18).div(lpSupply)
);
POOL_lastRewardBlock = block.number;
if(block.number >= POOL_MULTIPLIER_UPDATED.add(POOL_MULTIPLIER_UPDATE_1WEEK)){
POOL_MULTIPLIER = POOL_MULTIPLIER.mul(3).div(4);
POOL_MULTIPLIER_UPDATED = block.number;
}
}
function POOL_update() private {
uint lpSupply = lpToken.balanceOf(address(this));
if (POOL_lastRewardBlock == 0 || lpSupply == 0) {
POOL_lastRewardBlock = block.number;
return;
}
uint reward = CalculateReward(POOL_lastRewardBlock, block.number);
POOL_accTokensPerLP = POOL_accTokensPerLP.add(
reward.mul(1e18).div(lpSupply)
);
POOL_lastRewardBlock = block.number;
if(block.number >= POOL_MULTIPLIER_UPDATED.add(POOL_MULTIPLIER_UPDATE_1WEEK)){
POOL_MULTIPLIER = POOL_MULTIPLIER.mul(3).div(4);
POOL_MULTIPLIER_UPDATED = block.number;
}
}
function UserPendingReward() external view returns(uint){
return _POOL_pendingReward(users[msg.sender]);
}
function _POOL_pendingReward(User memory u) private view returns(uint){
uint _POOL_accTokensPerLP = POOL_accTokensPerLP;
uint lpSupply = lpToken.balanceOf(address(this));
if (block.number > POOL_lastRewardBlock && lpSupply != 0) {
uint pendingReward = CalculateReward(POOL_lastRewardBlock, block.number);
_POOL_accTokensPerLP = _POOL_accTokensPerLP.add(
pendingReward.mul(1e18).div(lpSupply)
);
}
return u.POOL_provided.mul(_POOL_accTokensPerLP).div(1e18)
.sub(u.POOL_rewardDebt);
}
function _POOL_pendingReward(User memory u) private view returns(uint){
uint _POOL_accTokensPerLP = POOL_accTokensPerLP;
uint lpSupply = lpToken.balanceOf(address(this));
if (block.number > POOL_lastRewardBlock && lpSupply != 0) {
uint pendingReward = CalculateReward(POOL_lastRewardBlock, block.number);
_POOL_accTokensPerLP = _POOL_accTokensPerLP.add(
pendingReward.mul(1e18).div(lpSupply)
);
}
return u.POOL_provided.mul(_POOL_accTokensPerLP).div(1e18)
.sub(u.POOL_rewardDebt);
}
function Harvest() external{
require(block.number >= POOL_START, "Pool hasn't started yet.");
_POOL_harvest(msg.sender);
}
function _POOL_harvest(address a) private{
User storage u = users[a];
uint pending = _POOL_pendingReward(u);
POOL_update();
if(pending > 0){
SafeTokenTransfer(a, pending);
}
u.POOL_rewardDebt = u.POOL_provided.mul(POOL_accTokensPerLP).div(1e18);
}
function _POOL_harvest(address a) private{
User storage u = users[a];
uint pending = _POOL_pendingReward(u);
POOL_update();
if(pending > 0){
SafeTokenTransfer(a, pending);
}
u.POOL_rewardDebt = u.POOL_provided.mul(POOL_accTokensPerLP).div(1e18);
}
function Stake(uint256 amount) external {
require(tx.origin == msg.sender, "Contracts not allowed.");
require(block.number >= POOL_START, "Pool hasn't started yet.");
require(amount > 0, "Must stake > 0 lp.");
_POOL_harvest(msg.sender);
lpToken.transferFrom(msg.sender, address(this), amount);
User storage u = users[msg.sender];
u.POOL_provided = u.POOL_provided.add(amount);
u.POOL_rewardDebt = u.POOL_provided.mul(POOL_accTokensPerLP).div(1e18);
}
function Unstake(uint amount) external{
User storage u = users[msg.sender];
require(amount > 0, "Unstaking 0 lp.");
require(u.POOL_provided >= amount, "Unstaking more than currently staked.");
_POOL_harvest(msg.sender);
lpToken.transfer(msg.sender, amount);
u.POOL_provided = u.POOL_provided.sub(amount);
u.POOL_rewardDebt = u.POOL_provided.mul(POOL_accTokensPerLP).div(1e18);
}
function SafeTokenTransfer(address _to, uint _amount) private {
uint bal = token.balanceOf(address(this));
if (_amount > bal) {
token.transfer(_to, bal);
token.transfer(_to, _amount);
}
}
function SafeTokenTransfer(address _to, uint _amount) private {
uint bal = token.balanceOf(address(this));
if (_amount > bal) {
token.transfer(_to, bal);
token.transfer(_to, _amount);
}
}
} else {
function getEthPrice() public view returns(uint) {
(uint112 reserves0, uint112 reserves1, ) = ETH_USDC_PAIR.getReserves();
uint reserveUSDC;
uint reserveETH;
if(WETH == ETH_USDC_PAIR.token0()){
reserveETH = reserves0;
reserveUSDC = reserves1;
reserveUSDC = reserves0;
reserveETH = reserves1;
}
}
function getEthPrice() public view returns(uint) {
(uint112 reserves0, uint112 reserves1, ) = ETH_USDC_PAIR.getReserves();
uint reserveUSDC;
uint reserveETH;
if(WETH == ETH_USDC_PAIR.token0()){
reserveETH = reserves0;
reserveUSDC = reserves1;
reserveUSDC = reserves0;
reserveETH = reserves1;
}
}
}else{
return reserveUSDC.mul(1e12).mul(PRECISION).div(reserveETH);
function getMASKEDPriceEth() public view returns(uint) {
(uint112 reserves0, uint112 reserves1, ) = lpToken.getReserves();
uint reserveETH;
uint reserveMASKED;
if(WETH == lpToken.token0()){
reserveETH = reserves0;
reserveMASKED = reserves1;
reserveMASKED = reserves0;
reserveETH = reserves1;
}
return reserveETH.mul(PRECISION).div(reserveMASKED);
}
function getMASKEDPriceEth() public view returns(uint) {
(uint112 reserves0, uint112 reserves1, ) = lpToken.getReserves();
uint reserveETH;
uint reserveMASKED;
if(WETH == lpToken.token0()){
reserveETH = reserves0;
reserveMASKED = reserves1;
reserveMASKED = reserves0;
reserveETH = reserves1;
}
return reserveETH.mul(PRECISION).div(reserveMASKED);
}
}else{
function GetMultiplier() public view returns (uint) {
if(block.number < POOL_START){
return 0;
}
return POOL_MULTIPLIER;
}
function GetMultiplier() public view returns (uint) {
if(block.number < POOL_START){
return 0;
}
return POOL_MULTIPLIER;
}
function SetMultiplier(uint256 newMultiplier) public {
POOL_MULTIPLIER = newMultiplier;
}
function Provided() external view returns(uint) {
return users[msg.sender].POOL_provided;
}
function PoolTotalValue() public view returns(uint) {
if(lpToken.totalSupply() == 0)
return 0;
(uint112 reserves0, uint112 reserves1, ) = lpToken.getReserves();
uint reserveEth;
if(WETH == lpToken.token0())
reserveEth = reserves0;
else
reserveEth = reserves1;
uint lpPriceEth = reserveEth.mul(1e5).mul(2).div(lpToken.totalSupply());
uint lpPriceUsd = lpPriceEth.mul(getEthPrice()).div(1e5);
return lpToken.balanceOf(address(this)).mul(lpPriceUsd).div(1e18);
}
function PoolAPY() external view returns(uint){
return POOL_MULTIPLIER.mul(2336000).mul(getMASKEDPriceEth()).mul(getEthPrice()).mul(100).div(PoolTotalValue());
}
if(PoolTotalValue() == 0){ return 0; }
} | 8,220,404 | [
1,
16444,
55,
473,
24023,
55,
404,
18,
13899,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
16698,
329,
42,
4610,
310,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
1758,
389,
70,
321,
12003,
31,
203,
565,
1758,
1071,
389,
8443,
31,
203,
377,
203,
565,
16698,
329,
1358,
1071,
1147,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
4154,
1071,
12423,
1345,
31,
203,
203,
565,
2254,
1071,
13803,
1741,
67,
24683,
2053,
654,
67,
8217,
40,
31,
203,
565,
2254,
1071,
13803,
1741,
67,
2722,
17631,
1060,
1768,
31,
203,
203,
565,
2254,
1071,
11732,
13803,
1741,
67,
7570,
31,
203,
565,
2254,
1071,
5381,
13803,
1741,
67,
7570,
67,
26101,
273,
404,
31,
203,
565,
2254,
1071,
5381,
7071,
26913,
273,
404,
73,
25,
31,
203,
203,
565,
1758,
5381,
678,
1584,
44,
273,
374,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
31,
203,
565,
467,
984,
291,
91,
438,
58,
22,
4154,
5381,
512,
2455,
67,
3378,
5528,
67,
4066,
7937,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
20,
20029,
24,
73,
2313,
72,
1611,
9470,
73,
9401,
72,
4763,
23508,
10160,
22,
71,
26,
30489,
70,
6334,
6030,
21,
23057,
6030,
39,
29,
40,
71,
1769,
203,
377,
203,
565,
1958,
2177,
288,
203,
3639,
2254,
13803,
1741,
67,
29206,
31,
203,
3639,
2254,
13803,
1741,
67,
266,
2913,
758,
23602,
31,
203,
565,
289,
203,
377,
203,
565,
2874,
2
] |
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.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @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 `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* 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 IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
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 `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @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 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @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 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
/**
* @title SDOGEERC20Token
* @author SDOGE
*
* @dev Standard ERC20 token with burning and optional functions implemented.
* For full specification of ERC-20 standard see:
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract SOGEERC20Token is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Constructor.
* @param name name of the token
* @param symbol symbol of the token, 3-4 chars is recommended
* @param decimals number of decimal places of one token unit, 18 is widely used
* @param totalSupply total supply of tokens in lowest units (depending on decimals)
* @param tokenOwnerAddress address that gets 100% of token supply
*/
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable {
_name = name;
_symbol = symbol;
_decimals = decimals;
// set tokenOwnerAddress as owner of all tokens
_mint(tokenOwnerAddress, totalSupply);
// pay the service fee for contract deployment
feeReceiver.transfer(msg.value);
}
/**
* @dev Burns a specific amount of tokens.
* @param value The amount of lowest token units to be burned.
*/
function burn(uint256 value) public {
_burn(msg.sender, value);
}
// optional functions from ERC20 stardard
/**
* @return the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
} | * @title SDOGEERC20Token @author SDOGE @dev Standard ERC20 token with burning and optional functions implemented. For full specification of ERC-20 standard see:/ | contract SOGEERC20Token is ERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply, address payable feeReceiver, address tokenOwnerAddress) public payable {
_name = name;
_symbol = symbol;
_decimals = decimals;
_mint(tokenOwnerAddress, totalSupply);
feeReceiver.transfer(msg.value);
}
function burn(uint256 value) public {
_burn(msg.sender, value);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
} | 1,343,069 | [
1,
55,
3191,
7113,
654,
39,
3462,
1345,
225,
348,
3191,
7113,
225,
8263,
4232,
39,
3462,
1147,
598,
18305,
310,
471,
3129,
4186,
8249,
18,
2457,
1983,
7490,
434,
4232,
39,
17,
3462,
4529,
2621,
27824,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7460,
7113,
654,
39,
3462,
1345,
353,
4232,
39,
3462,
288,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
565,
3885,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
16,
2254,
28,
15105,
16,
2254,
5034,
2078,
3088,
1283,
16,
1758,
8843,
429,
14036,
12952,
16,
1758,
1147,
5541,
1887,
13,
1071,
8843,
429,
288,
203,
1377,
389,
529,
273,
508,
31,
203,
1377,
389,
7175,
273,
3273,
31,
203,
1377,
389,
31734,
273,
15105,
31,
203,
203,
1377,
389,
81,
474,
12,
2316,
5541,
1887,
16,
2078,
3088,
1283,
1769,
203,
203,
1377,
14036,
12952,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
11890,
5034,
460,
13,
1071,
288,
203,
1377,
389,
70,
321,
12,
3576,
18,
15330,
16,
460,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
1377,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
1377,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
1377,
327,
389,
31734,
31,
203,
565,
289,
203,
97,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x496486Bcf8E7924610819d3E65Bd0f64825Fd3D9/sources/contracts/bonding-curves/LinearCurve.sol | We first calculate the change in spot price after selling all of the items | uint256 totalPriceDecrease = delta * numItems;
| 13,243,011 | [
1,
3218,
1122,
4604,
326,
2549,
316,
16463,
6205,
1839,
357,
2456,
777,
434,
326,
1516,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
2078,
5147,
23326,
448,
273,
3622,
380,
818,
3126,
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
] |
./partial_match/42/0xF0439F1508F9329B30e7067703cd3FeD02696740/sources/EtherCollateralsUSD.sol | compound accrued interest with remaining loanAmount * (now - lastTimestampInterestPaid) Get the loan from storage | function currentInterestOnLoan(address _account, uint256 _loanID) external view returns (uint256) {
SynthLoanStruct memory synthLoan = _getLoanFromStorage(_account, _loanID);
uint256 currentInterest = accruedInterestOnLoan(
synthLoan.loanAmount.add(synthLoan.accruedInterest),
_timeSinceInterestAccrual(synthLoan)
);
return synthLoan.accruedInterest.add(currentInterest);
}
| 3,395,437 | [
1,
22585,
4078,
86,
5957,
16513,
598,
4463,
28183,
6275,
225,
261,
3338,
300,
1142,
4921,
29281,
16507,
350,
13,
968,
326,
28183,
628,
2502,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
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,
783,
29281,
1398,
1504,
304,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
383,
304,
734,
13,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
16091,
451,
1504,
304,
3823,
3778,
6194,
451,
1504,
304,
273,
389,
588,
1504,
304,
1265,
3245,
24899,
4631,
16,
389,
383,
304,
734,
1769,
203,
3639,
2254,
5034,
783,
29281,
273,
4078,
86,
5957,
29281,
1398,
1504,
304,
12,
203,
5411,
6194,
451,
1504,
304,
18,
383,
304,
6275,
18,
1289,
12,
11982,
451,
1504,
304,
18,
8981,
86,
5957,
29281,
3631,
203,
5411,
389,
957,
9673,
29281,
8973,
86,
1462,
12,
11982,
451,
1504,
304,
13,
203,
3639,
11272,
203,
3639,
327,
6194,
451,
1504,
304,
18,
8981,
86,
5957,
29281,
18,
1289,
12,
2972,
29281,
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
] |
./partial_match/42/0xAf5d2BC0A47f0aE99b7E7225349e3d5C48F46Fd5/sources/STERegistryV1.sol | * @notice Gets the owner of the contract @return address owner/ | function owner() public view returns(address) {
return getAddressValue(OWNER);
}
| 3,412,198 | [
1,
3002,
326,
3410,
434,
326,
6835,
327,
1758,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1435,
1071,
1476,
1135,
12,
2867,
13,
288,
203,
3639,
327,
14808,
620,
12,
29602,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "base64-sol/base64.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "./IAchievement.sol";
import "./AchievementModel.sol";
import "hardhat/console.sol";
/**
* @title Achievement
* @author @StErMi
* @notice A general purpose Achievement System for the FTM ecosystem
*/
contract Achievement is ERC721Enumerable {
using Strings for uint256;
using Counters for Counters.Counter;
/// @notice Metadata ID tracker
Counters.Counter private _metadataId;
/// @notice Achievement ID tracker
Counters.Counter private _achievementId;
/// @notice Registered achievement metadats from contracts
mapping(uint256 => AchievementModel.Metadata) private metadatas;
/// @notice List of achievements awarded to a user
mapping(address => AchievementModel.Achievement[]) private userAchievements;
/// @notice NFT ID -> Achievement tracker
mapping(uint256 => AchievementModel.Achievement) private achievements;
/// @notice Fast check ownership of an achievement metadata
mapping(address => mapping(uint256 => bool)) private _ownerships;
/// @notice event emitted when an achievement is awarded to a user
event AchievementAwarded(
address indexed receiver,
uint256 indexed tokenId,
uint256 indexed metadataId,
address source,
string sourceName,
AchievementModel.Rarity rarity,
string title,
uint256 points,
uint256 timestamp
);
/// @notice event emitted when an achievement metadata is registered by a contract
event AchievementRegistered(
address indexed source,
uint256 indexed metadataId,
string sourceName,
AchievementModel.Rarity rarity,
string title,
uint256 points
);
/// @notice Constructor
constructor() ERC721("FTM Achievement", "FTMACK") {}
/**
* @notice Function used by external contract to register achievement metadata
* @param metadata Metadata of the achievement
* @return metadataId The ID of the registered achievement metadata
*/
function registerAchievement(AchievementModel.Metadata memory metadata) external returns (uint256 metadataId) {
checkMetadata(metadata);
_metadataId.increment();
metadata.source = msg.sender;
metadata.id = _metadataId.current();
metadatas[metadata.id] = metadata;
emit AchievementRegistered(
metadata.source,
metadata.id,
metadata.sourceName,
metadata.rarity,
metadata.title,
metadata.points
);
return metadata.id;
}
/**
* @notice Function used by external contract to award an achievement to a receiving wallet
* @param receiver Address of the wallet that will receive the achievement
* @param metadataId ID of the achievement metadata
*/
function awardAchievement(address receiver, uint256 metadataId)
external
returns (bool success, string memory failMessage)
{
AchievementModel.Metadata storage metadata = metadatas[metadataId];
if (metadata.source == address(0)) return (false, "Requested metadata not exist");
if (metadata.source != msg.sender) return (false, "You are not the owner of the metadata");
if (receiver == msg.sender) return (false, "Source can't award itself");
if (_ownerships[receiver][metadataId] == true) return (false, "Wallet already own the achievement");
// get the current achievement ID
uint256 currentAchievementId = _achievementId.current();
// Add the ownership to the summoner
_ownerships[receiver][metadataId] = true;
// Add the achievement to the summoner's list
uint256 timestamp = block.timestamp;
// AchievementModel.Achievement storage achievement = AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp);
userAchievements[receiver].push(
AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp)
);
achievements[currentAchievementId] = AchievementModel.Achievement(
metadataId,
currentAchievementId,
receiver,
timestamp
);
emit AchievementAwarded(
receiver,
currentAchievementId,
metadataId,
metadata.source,
metadata.sourceName,
metadata.rarity,
metadata.title,
metadata.points,
timestamp
);
_safeMint(receiver, currentAchievementId);
_achievementId.increment();
return (true, "");
}
/////////////////////////
// External Utilities
/////////////////////////
/**
* @notice Get achievement metadata by providing a metadataId
* @param metadataId ID of the achievement metadata
* @return List of achievements
*/
function getMetadata(uint256 metadataId) external view returns (AchievementModel.Metadata memory) {
return metadatas[metadataId];
}
/**
* @notice Get achievement expanded information by providing a achievementId
* @param achievementId ID of the achievement
* @return Data of the requested achievement
*/
function getAchievement(uint256 achievementId) external view returns (AchievementModel.AchievementExpanded memory) {
AchievementModel.Achievement storage _achievement = achievements[achievementId];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
return
AchievementModel.AchievementExpanded({
metadata: metadata,
achievementId: achievementId,
user: _achievement.user,
timestamp: _achievement.timestamp
});
}
/**
* @notice Check if a user has been awarded with an achievement
* @param user Address of the user
* @param metadataId Achievement Metadata ID
* @return true if he already has the achievement
*/
function hasAchievement(address user, uint256 metadataId) external view returns (bool) {
return _ownerships[user][metadataId];
}
/**
* @notice Get the total achievement points collected by the summoner
* @param user Address of the user
* @param sources List of whitelisted contracts to filter achievements with. Can be empty.
* @return amount of achievement points
*/
function getPoints(address user, address[] memory sources) external view returns (uint256) {
(, , uint256 points) = filterAchievements(user, sources);
return points;
}
/**
* @notice Get list of achievements owned by the summoner
* @param user Address of the user
* @param sources List of whitelisted contracts to filter achievements with. Can be empty.
* @param offset Position from which start
* @param limit Amount of achievements to return
* @return List of achievements owned by the user
*/
function getAchievements(
address user,
address[] memory sources,
uint256 offset,
uint256 limit
) external view returns (AchievementModel.AchievementExpanded[] memory) {
(AchievementModel.AchievementExpanded[] memory _tempList, uint256 maxWhitelistedLength, ) = filterAchievements(
user,
sources
);
uint256 safeLimit = limit == 0 ? 2**32 - 1 : limit;
if (safeLimit > maxWhitelistedLength) {
require(maxWhitelistedLength >= offset, "Offset is greater than number of records available");
}
uint256 maxLen = safeLimit > maxWhitelistedLength ? maxWhitelistedLength - offset : safeLimit;
AchievementModel.AchievementExpanded[] memory _achievements = new AchievementModel.AchievementExpanded[](
maxLen
);
for (uint256 i = 0; i < maxLen; i++) {
_achievements[i] = _tempList[offset + i];
}
return _achievements;
}
/////////////////////////
// Internal Utilities
/////////////////////////
/**
* @dev Filter summoner's achievement by the list of whitelisted sources
*/
function filterAchievements(address user, address[] memory sources)
internal
view
returns (
AchievementModel.AchievementExpanded[] memory,
uint256,
uint256
)
{
// Get the correct length
uint256 achievementCount = userAchievements[user].length;
uint256 points = 0;
AchievementModel.AchievementExpanded[] memory _tempList = new AchievementModel.AchievementExpanded[](
achievementCount
);
uint256 maxWhitelistedLength = 0;
for (uint256 i = 0; i < achievementCount; i++) {
AchievementModel.Achievement storage _achievement = userAchievements[user][i];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
bool whitelisted = false;
if (sources.length > 0) {
for (uint256 j = 0; j < sources.length; j++) {
if (metadata.source == sources[j]) {
whitelisted = true;
break;
}
}
if (whitelisted == false) {
// skip this achivement
continue;
}
}
points += metadata.points;
AchievementModel.AchievementExpanded memory achievement = AchievementModel.AchievementExpanded({
metadata: metadata,
achievementId: _achievement.achievementId,
user: _achievement.user,
timestamp: _achievement.timestamp
});
_tempList[maxWhitelistedLength] = achievement;
maxWhitelistedLength++;
}
return (_tempList, maxWhitelistedLength, points);
}
/**
* @dev Check the integrity of a achievement metadata
*/
function checkMetadata(AchievementModel.Metadata memory _metadata) internal pure {
require(
_metadata.rarity >= AchievementModel.Rarity.Common && _metadata.rarity <= AchievementModel.Rarity.Legendary,
"Invalid rarity"
);
require(bytes(_metadata.sourceName).length > 0, "Source Name must not be empty");
require(bytes(_metadata.title).length > 0, "Title must not be empty");
require(bytes(_metadata.description).length > 0, "Description must not be empty");
require(_metadata.points > 0, "Points must be greater than 0");
}
/////////////////////////
// ERC721 overrides
/////////////////////////
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "token does not exist");
AchievementModel.Achievement storage _achievement = achievements[tokenId];
AchievementModel.Metadata memory metadata = metadatas[_achievement.metadataId];
string[11] memory parts;
parts[
0
] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: serif; font-size: 14px; }</style><rect width="100%" height="100%" fill="black" /><text x="10" y="20" class="base">';
parts[1] = string(abi.encodePacked("Source: ", metadata.sourceName));
parts[2] = '</text><text x="10" y="40" class="base">';
parts[3] = string(abi.encodePacked("Title: ", metadata.title));
parts[4] = '</text><text x="10" y="60" class="base">';
parts[5] = string(abi.encodePacked("Description: ", metadata.description));
parts[6] = '</text><text x="10" y="80" class="base">';
parts[7] = string(abi.encodePacked("Rarity: ", uint256(metadata.rarity).toString()));
parts[8] = '</text><text x="10" y="100" class="base">';
parts[9] = string(abi.encodePacked("Points: ", metadata.points.toString()));
parts[10] = "</text></svg>";
string memory output = string(
abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8])
);
output = string(abi.encodePacked(output, parts[9], parts[10]));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Archievement #',
tokenId.toString(),
'", "description": "FTM Achievement to track user achievements and engagement with the platform", "image": "data:image/svg+xml;base64,',
Base64.encode(bytes(output)),
'"}'
)
)
)
);
output = string(abi.encodePacked("data:application/json;base64,", json));
return output;
}
/**
* @dev Hook that is called before any token transfer. Check if the user has the NFT locked
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Enumerable) {
// Archievement can be minted but it cannot be transferred to other users, it's soulbound to the person
require(from == address(0), "The Archievement NFT is soul bound to the user");
super._beforeTokenTransfer(from, to, tokenId);
}
}
| * @notice Function used by external contract to award an achievement to a receiving wallet @param receiver Address of the wallet that will receive the achievement @param metadataId ID of the achievement metadata/ get the current achievement ID Add the ownership to the summoner Add the achievement to the summoner's list AchievementModel.Achievement storage achievement = AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp); | function awardAchievement(address receiver, uint256 metadataId)
external
returns (bool success, string memory failMessage)
{
AchievementModel.Metadata storage metadata = metadatas[metadataId];
if (metadata.source == address(0)) return (false, "Requested metadata not exist");
if (metadata.source != msg.sender) return (false, "You are not the owner of the metadata");
if (receiver == msg.sender) return (false, "Source can't award itself");
if (_ownerships[receiver][metadataId] == true) return (false, "Wallet already own the achievement");
uint256 currentAchievementId = _achievementId.current();
_ownerships[receiver][metadataId] = true;
uint256 timestamp = block.timestamp;
userAchievements[receiver].push(
AchievementModel.Achievement(metadataId, currentAchievementId, receiver, timestamp)
);
achievements[currentAchievementId] = AchievementModel.Achievement(
metadataId,
currentAchievementId,
receiver,
timestamp
);
emit AchievementAwarded(
receiver,
currentAchievementId,
metadataId,
metadata.source,
metadata.sourceName,
metadata.rarity,
metadata.title,
metadata.points,
timestamp
);
_safeMint(receiver, currentAchievementId);
_achievementId.increment();
return (true, "");
}
| 6,436,315 | [
1,
2083,
1399,
635,
3903,
6835,
358,
279,
2913,
392,
20186,
22627,
358,
279,
15847,
9230,
225,
5971,
5267,
434,
326,
9230,
716,
903,
6798,
326,
20186,
22627,
225,
1982,
548,
1599,
434,
326,
20186,
22627,
1982,
19,
336,
326,
783,
20186,
22627,
1599,
1436,
326,
23178,
358,
326,
2142,
2586,
264,
1436,
326,
20186,
22627,
358,
326,
2142,
2586,
264,
1807,
666,
432,
17384,
22627,
1488,
18,
37,
17384,
22627,
2502,
20186,
22627,
273,
432,
17384,
22627,
1488,
18,
37,
17384,
22627,
12,
4165,
548,
16,
783,
37,
17384,
22627,
548,
16,
5971,
16,
2858,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
279,
2913,
37,
17384,
22627,
12,
2867,
5971,
16,
2254,
5034,
1982,
548,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
6430,
2216,
16,
533,
3778,
2321,
1079,
13,
203,
565,
288,
203,
3639,
432,
17384,
22627,
1488,
18,
2277,
2502,
1982,
273,
312,
24484,
63,
4165,
548,
15533,
203,
203,
3639,
309,
261,
4165,
18,
3168,
422,
1758,
12,
20,
3719,
327,
261,
5743,
16,
315,
11244,
1982,
486,
1005,
8863,
203,
3639,
309,
261,
4165,
18,
3168,
480,
1234,
18,
15330,
13,
327,
261,
5743,
16,
315,
6225,
854,
486,
326,
3410,
434,
326,
1982,
8863,
203,
3639,
309,
261,
24454,
422,
1234,
18,
15330,
13,
327,
261,
5743,
16,
315,
1830,
848,
1404,
279,
2913,
6174,
8863,
203,
3639,
309,
261,
67,
995,
12565,
87,
63,
24454,
6362,
4165,
548,
65,
422,
638,
13,
327,
261,
5743,
16,
315,
16936,
1818,
4953,
326,
20186,
22627,
8863,
203,
203,
3639,
2254,
5034,
783,
37,
17384,
22627,
548,
273,
389,
497,
1385,
22627,
548,
18,
2972,
5621,
203,
203,
3639,
389,
995,
12565,
87,
63,
24454,
6362,
4165,
548,
65,
273,
638,
31,
203,
203,
3639,
2254,
5034,
2858,
273,
1203,
18,
5508,
31,
203,
3639,
729,
37,
17384,
90,
17110,
63,
24454,
8009,
6206,
12,
203,
5411,
432,
17384,
22627,
1488,
18,
37,
17384,
22627,
12,
4165,
548,
16,
783,
37,
17384,
22627,
548,
16,
5971,
16,
2858,
13,
203,
3639,
11272,
203,
3639,
20186,
90,
17110,
63,
2972,
37,
17384,
22627,
548,
65,
273,
432,
17384,
22627,
1488,
18,
2
] |
// SPDX-License-Identifier: MIT
// ChargedSettings.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IChargedSettings.sol";
import "./lib/Bitwise.sol";
import "./lib/TokenInfo.sol";
import "./lib/RelayRecipient.sol";
import "./lib/BlackholePrevention.sol";
/**
* @notice Charged Particles Settings Contract
*/
contract ChargedSettings is
IChargedSettings,
Ownable,
RelayRecipient,
BlackholePrevention
{
using SafeMath for uint256;
using TokenInfo for address;
using Bitwise for uint32;
uint256 constant internal MAX_ANNUITIES = 1e4; // 10000 (100%)
// NftSettings - actionPerms
uint32 constant internal PERM_CHARGE_NFT = 1; // NFT Contracts that can have assets Deposited into them (Charged)
uint32 constant internal PERM_BASKET_NFT = 2; // NFT Contracts that can have other NFTs Deposited into them
uint32 constant internal PERM_TIMELOCK_ANY_NFT = 4; // NFT Contracts that can timelock any NFT on behalf of users (primarily used for Front-run Protection)
uint32 constant internal PERM_TIMELOCK_OWN_NFT = 8; // NFT Contracts that can timelock their own NFTs on behalf of their users
uint32 constant internal PERM_RESTRICTED_ASSETS = 16; // NFT Contracts that have restricted deposits to specific assets
// Current Settings for External NFT Token Contracts;
// - Any user can add any ERC721 or ERC1155 token as a Charged Particle without Limits,
// unless the Owner of the ERC721 or ERC1155 token contract registers the token
// and sets the Custom Settings for their token(s)
struct NftSettings {
uint32 actionPerms;
string requiredWalletManager;
string requiredBasketManager;
// ERC20
mapping (address => bool) allowedAssetTokens;
mapping (address => uint256) depositMin; // Asset Token Address => Min
mapping (address => uint256) depositMax; // Asset Token Address => Max
// ERC721 / ERC1155
mapping (address => uint256) maxNfts; // NFT Token Address => Max
}
// Optional Configs for individual NFTs set by NFT Creator
struct CreatorSettings {
uint256 annuityPercent;
address annuityRedirect;
}
mapping (address => uint256) internal _depositCap;
uint256 internal _tempLockExpiryBlocks;
// Wallet/Basket Managers (by Unique Manager ID)
mapping (string => IWalletManager) internal _ftWalletManager;
mapping (string => IBasketManager) internal _nftBasketManager;
// Settings for individual NFTs set by NFT Creator (by Token UUID)
mapping (uint256 => CreatorSettings) internal _creatorSettings;
// Settings for External NFT Token Contracts (by Token Contract Address)
mapping (address => NftSettings) internal _nftSettings;
/***********************************|
| Public |
|__________________________________*/
/// @notice Checks if an Account is the Owner of an NFT Contract
/// When Custom Contracts are registered, only the "owner" or operator of the Contract
/// is allowed to register them and define custom rules for how their tokens are "Charged".
/// Otherwise, any token can be "Charged" according to the default rules of Charged Particles.
/// @param contractAddress The Address to the External NFT Contract to check
/// @param account The Account to check if it is the Owner of the specified Contract
/// @return True if the account is the Owner of the _contract
function isContractOwner(address contractAddress, address account) external view override virtual returns (bool) {
return contractAddress.isContractOwner(account);
}
function isWalletManagerEnabled(string calldata walletManagerId) external virtual override view returns (bool) {
return _isWalletManagerEnabled(walletManagerId);
}
function getWalletManager(string calldata walletManagerId) external virtual override view returns (IWalletManager) {
return _ftWalletManager[walletManagerId];
}
function isNftBasketEnabled(string calldata basketId) external virtual override view returns (bool) {
return _isNftBasketEnabled(basketId);
}
function getBasketManager(string calldata basketId) external virtual override view returns (IBasketManager) {
return _nftBasketManager[basketId];
}
/// @dev Gets the amount of creator annuities reserved for the creator for the specified NFT
/// @param contractAddress The Address to the Contract of the NFT
/// @param tokenId The Token ID of the NFT
/// @return creator The address of the creator
/// @return annuityPct The percentage amount of annuities reserved for the creator
function getCreatorAnnuities(
address contractAddress,
uint256 tokenId
)
external
view
override
virtual
returns (address creator, uint256 annuityPct)
{
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
creator = contractAddress.getTokenCreator(tokenId);
annuityPct = _creatorSettings[tokenUuid].annuityPercent;
}
function getCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId)
external
view
override
virtual
returns (address)
{
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
return _creatorSettings[tokenUuid].annuityRedirect;
}
function getTempLockExpiryBlocks() external view override virtual returns (uint256) {
return _tempLockExpiryBlocks;
}
function getTimelockApprovals(address operator)
external
view
override
virtual
returns (bool timelockAny, bool timelockOwn)
{
timelockAny = _nftSettings[operator].actionPerms.hasBit(PERM_TIMELOCK_ANY_NFT);
timelockOwn = _nftSettings[operator].actionPerms.hasBit(PERM_TIMELOCK_OWN_NFT);
}
function getAssetRequirements(address contractAddress, address assetToken)
external
view
override
virtual
returns (
string memory requiredWalletManager,
bool energizeEnabled,
bool restrictedAssets,
bool validAsset,
uint256 depositCap,
uint256 depositMin,
uint256 depositMax
)
{
requiredWalletManager = _nftSettings[contractAddress].requiredWalletManager;
energizeEnabled = _nftSettings[contractAddress].actionPerms.hasBit(PERM_CHARGE_NFT);
restrictedAssets = _nftSettings[contractAddress].actionPerms.hasBit(PERM_RESTRICTED_ASSETS);
validAsset = _nftSettings[contractAddress].allowedAssetTokens[assetToken];
depositCap = _depositCap[assetToken];
depositMin = _nftSettings[contractAddress].depositMin[assetToken];
depositMax = _nftSettings[contractAddress].depositMax[assetToken];
}
function getNftAssetRequirements(address contractAddress, address nftTokenAddress)
external
view
override
virtual
returns (string memory requiredBasketManager, bool basketEnabled, uint256 maxNfts)
{
requiredBasketManager = _nftSettings[contractAddress].requiredBasketManager;
basketEnabled = _nftSettings[contractAddress].actionPerms.hasBit(PERM_BASKET_NFT);
maxNfts = _nftSettings[contractAddress].maxNfts[nftTokenAddress];
}
/***********************************|
| Only NFT Creator |
|__________________________________*/
/// @notice Sets the Custom Configuration for Creators of Proton-based NFTs
/// @param contractAddress The Address to the Proton-based NFT to configure
/// @param tokenId The token ID of the Proton-based NFT to configure
/// @param creator The creator of the Proton-based NFT
/// @param annuityPercent The percentage of interest-annuities to reserve for the creator
function setCreatorAnnuities(
address contractAddress,
uint256 tokenId,
address creator,
uint256 annuityPercent
)
external
virtual
override
{
require(contractAddress.isTokenContractOrCreator(tokenId, creator, _msgSender()), "CP:E-104");
require(annuityPercent <= MAX_ANNUITIES, "CP:E-421");
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
// Update Configs for External Token Creator
_creatorSettings[tokenUuid].annuityPercent = annuityPercent;
emit TokenCreatorConfigsSet(
contractAddress,
tokenId,
creator,
annuityPercent
);
}
/// @notice Sets a Custom Receiver Address for the Creator Annuities
/// @param contractAddress The Address to the Proton-based NFT to configure
/// @param tokenId The token ID of the Proton-based NFT to configure
/// @param creator The creator of the Proton-based NFT
/// @param receiver The receiver of the Creator interest-annuities
function setCreatorAnnuitiesRedirect(
address contractAddress,
uint256 tokenId,
address creator,
address receiver
)
external
virtual
override
{
require(contractAddress.isTokenContractOrCreator(tokenId, creator, _msgSender()), "CP:E-104");
uint256 tokenUuid = contractAddress.getTokenUUID(tokenId);
_creatorSettings[tokenUuid].annuityRedirect = receiver;
emit TokenCreatorAnnuitiesRedirected(contractAddress, tokenId, receiver);
}
function setTrustedForwarder(address _trustedForwarder) external onlyOwner {
trustedForwarder = _trustedForwarder;
}
/***********************************|
| Register Contract Settings |
|(For External Contract Integration)|
|__________________________________*/
/// @notice Sets a Required Wallet-Manager for External NFT Contracts (otherwise set to "none" to allow any Wallet-Manager)
/// @param contractAddress The Address to the External NFT Contract to configure
/// @param walletManager If set, will only allow deposits from this specific Wallet-Manager
function setRequiredWalletManager(
address contractAddress,
string calldata walletManager
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
if (keccak256(bytes(walletManager)) == keccak256(bytes("none"))) {
_nftSettings[contractAddress].requiredWalletManager = "";
} else {
_nftSettings[contractAddress].requiredWalletManager = walletManager;
}
emit RequiredWalletManagerSet(
contractAddress,
walletManager
);
}
/// @notice Sets a Required Basket-Manager for External NFT Contracts (otherwise set to "none" to allow any Basket-Manager)
/// @param contractAddress The Address to the External Contract to configure
/// @param basketManager If set, will only allow deposits from this specific Basket-Manager
function setRequiredBasketManager(
address contractAddress,
string calldata basketManager
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
if (keccak256(bytes(basketManager)) == keccak256(bytes("none"))) {
_nftSettings[contractAddress].requiredBasketManager = "";
} else {
_nftSettings[contractAddress].requiredBasketManager = basketManager;
}
emit RequiredBasketManagerSet(
contractAddress,
basketManager
);
}
/// @notice Enables or Disables Asset-Token Restrictions for External NFT Contracts
/// @param contractAddress The Address to the External NFT Contract to configure
/// @param restrictionsEnabled If set, will only allow deposits from Allowed Asset Tokens
function setAssetTokenRestrictions(
address contractAddress,
bool restrictionsEnabled
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
if (restrictionsEnabled) {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.setBit(PERM_RESTRICTED_ASSETS);
} else {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.clearBit(PERM_RESTRICTED_ASSETS);
}
emit AssetTokenRestrictionsSet(
contractAddress,
restrictionsEnabled
);
}
/// @notice Enables or Disables Allowed Asset Tokens for External NFT Contracts
/// @param contractAddress The Address to the External NFT Contract to configure
/// @param assetToken The Address of the Asset Token to Allow or Disallow
/// @param isAllowed True if the Asset Token is allowed
function setAllowedAssetToken(
address contractAddress,
address assetToken,
bool isAllowed
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
_nftSettings[contractAddress].allowedAssetTokens[assetToken] = isAllowed;
emit AllowedAssetTokenSet(
contractAddress,
assetToken,
isAllowed
);
}
/// @notice Sets the Custom Configuration for External Contracts
/// @param contractAddress The Address to the External Contract to configure
/// @param assetToken The address of the Asset Token to set Limits for
/// @param depositMin If set, will define the minimum amount of Asset tokens the NFT may hold, otherwise any amount
/// @param depositMax If set, will define the maximum amount of Asset tokens the NFT may hold, otherwise any amount
function setAssetTokenLimits(
address contractAddress,
address assetToken,
uint256 depositMin,
uint256 depositMax
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
_nftSettings[contractAddress].depositMin[assetToken] = depositMin;
_nftSettings[contractAddress].depositMax[assetToken] = depositMax;
emit AssetTokenLimitsSet(
contractAddress,
assetToken,
depositMin,
depositMax
);
}
/// @notice Sets the Max Number of NFTs that can be held by a Charged Particle NFT
/// @param contractAddress The Address to the External Contract to configure
/// @param nftTokenAddress The address of the NFT Token to set a Max for
/// @param maxNfts The maximum numbers of NFTs that can be held by a given NFT (0 = unlimited)
function setMaxNfts(
address contractAddress,
address nftTokenAddress,
uint256 maxNfts
)
external
virtual
override
onlyValidExternalContract(contractAddress)
onlyContractOwnerOrAdmin(contractAddress, msg.sender)
{
// Update Configs for External Token Contract
_nftSettings[contractAddress].maxNfts[nftTokenAddress] = maxNfts;
emit MaxNftsSet(
contractAddress,
nftTokenAddress,
maxNfts
);
}
/***********************************|
| Only Admin/DAO |
|__________________________________*/
function setDepositCap(address assetToken, uint256 cap) external virtual onlyOwner {
_depositCap[assetToken] = cap;
emit DepositCapSet(assetToken, cap);
}
function setTempLockExpiryBlocks(uint256 numBlocks) external virtual onlyOwner {
_tempLockExpiryBlocks = numBlocks;
emit TempLockExpirySet(numBlocks);
}
/// @dev Register Contracts as wallet managers with a unique liquidity provider ID
function registerWalletManager(string calldata walletManagerId, address walletManager) external virtual onlyOwner {
// Validate wallet manager
IWalletManager newWalletMgr = IWalletManager(walletManager);
require(newWalletMgr.isPaused() != true, "CP:E-418");
// Register LP ID
_ftWalletManager[walletManagerId] = newWalletMgr;
emit WalletManagerRegistered(walletManagerId, walletManager);
}
/// @dev Register Contracts as basket managers with a unique basket ID
function registerBasketManager(string calldata basketId, address basketManager) external virtual onlyOwner {
// Validate basket manager
IBasketManager newBasketMgr = IBasketManager(basketManager);
require(newBasketMgr.isPaused() != true, "CP:E-418");
// Register Basket ID
_nftBasketManager[basketId] = newBasketMgr;
emit BasketManagerRegistered(basketId, basketManager);
}
function enableNftContracts(address[] calldata contracts) external override virtual onlyOwner {
uint count = contracts.length;
for (uint i = 0; i < count; i++) {
address tokenContract = contracts[i];
_setPermsForCharge(tokenContract, true);
_setPermsForBasket(tokenContract, true);
_setPermsForTimelockSelf(tokenContract, true);
}
}
/// @dev Update the list of NFT contracts that can be Charged
function setPermsForCharge(address contractAddress, bool state)
external
override
virtual
onlyOwner
{
_setPermsForCharge(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can hold other NFTs
function setPermsForBasket(address contractAddress, bool state)
external
override
virtual
onlyOwner
{
_setPermsForBasket(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can Timelock any NFT for Front-run Protection
function setPermsForTimelockAny(address contractAddress, bool state)
external
override
virtual
onlyOwner
{
_setPermsForTimelockAny(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can Timelock their own tokens
function setPermsForTimelockSelf(address contractAddress, bool state)
external
override
virtual
onlyOwner
{
_setPermsForTimelockSelf(contractAddress, state);
}
/***********************************|
| Only Admin/DAO |
| (blackhole prevention) |
|__________________________________*/
function withdrawEther(address payable receiver, uint256 amount) external virtual onlyOwner {
_withdrawEther(receiver, amount);
}
function withdrawErc20(address payable receiver, address tokenAddress, uint256 amount) external virtual onlyOwner {
_withdrawERC20(receiver, tokenAddress, amount);
}
function withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) external virtual onlyOwner {
_withdrawERC721(receiver, tokenAddress, tokenId);
}
/***********************************|
| Private Functions |
|__________________________________*/
/// @dev See {ChargedParticles-isWalletManagerEnabled}.
function _isWalletManagerEnabled(string calldata walletManagerId) internal view virtual returns (bool) {
return (address(_ftWalletManager[walletManagerId]) != address(0x0) && !_ftWalletManager[walletManagerId].isPaused());
}
/// @dev See {ChargedParticles-isNftBasketEnabled}.
function _isNftBasketEnabled(string calldata basketId) internal view virtual returns (bool) {
return (address(_nftBasketManager[basketId]) != address(0x0) && !_nftBasketManager[basketId].isPaused());
}
/// @dev Update the list of NFT contracts that can be Charged
function _setPermsForCharge(address contractAddress, bool state) internal virtual {
if (state) {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.setBit(PERM_CHARGE_NFT);
} else {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.clearBit(PERM_CHARGE_NFT);
}
emit PermsSetForCharge(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can hold other NFTs
function _setPermsForBasket(address contractAddress, bool state) internal virtual {
if (state) {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.setBit(PERM_BASKET_NFT);
} else {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.clearBit(PERM_BASKET_NFT);
}
emit PermsSetForBasket(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can Timelock any NFT for Front-run Protection
function _setPermsForTimelockAny(address contractAddress, bool state) internal virtual {
if (state) {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.setBit(PERM_TIMELOCK_ANY_NFT);
} else {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.clearBit(PERM_TIMELOCK_ANY_NFT);
}
emit PermsSetForTimelockAny(contractAddress, state);
}
/// @dev Update the list of NFT contracts that can Timelock their own tokens
function _setPermsForTimelockSelf(address contractAddress, bool state) internal virtual {
if (state) {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.setBit(PERM_TIMELOCK_OWN_NFT);
} else {
_nftSettings[contractAddress].actionPerms = _nftSettings[contractAddress].actionPerms.clearBit(PERM_TIMELOCK_OWN_NFT);
}
emit PermsSetForTimelockSelf(contractAddress, state);
}
/***********************************|
| GSN/MetaTx Relay |
|__________________________________*/
/// @dev See {BaseRelayRecipient-_msgSender}.
function _msgSender()
internal
view
virtual
override(BaseRelayRecipient, Context)
returns (address payable)
{
return BaseRelayRecipient._msgSender();
}
/// @dev See {BaseRelayRecipient-_msgData}.
function _msgData()
internal
view
virtual
override(BaseRelayRecipient, Context)
returns (bytes memory)
{
return BaseRelayRecipient._msgData();
}
/***********************************|
| Modifiers |
|__________________________________*/
modifier onlyValidExternalContract(address contractAddress) {
require(contractAddress.isContract(), "CP:E-420");
_;
}
modifier onlyContractOwnerOrAdmin(address contractAddress, address sender) {
require(sender == owner() || contractAddress.isContractOwner(sender), "CP:E-103");
_;
}
}
// 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 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
// IChargedSettings.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "./IWalletManager.sol";
import "./IBasketManager.sol";
/**
* @notice Interface for Charged Settings
*/
interface IChargedSettings {
/***********************************|
| Public API |
|__________________________________*/
function isContractOwner(address contractAddress, address account) external view returns (bool);
function getCreatorAnnuities(address contractAddress, uint256 tokenId) external view returns (address creator, uint256 annuityPct);
function getCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId) external view returns (address);
function getTempLockExpiryBlocks() external view returns (uint256);
function getTimelockApprovals(address operator) external view returns (bool timelockAny, bool timelockOwn);
function getAssetRequirements(address contractAddress, address assetToken) external view
returns (string memory requiredWalletManager, bool energizeEnabled, bool restrictedAssets, bool validAsset, uint256 depositCap, uint256 depositMin, uint256 depositMax);
function getNftAssetRequirements(address contractAddress, address nftTokenAddress) external view
returns (string memory requiredBasketManager, bool basketEnabled, uint256 maxNfts);
// ERC20
function isWalletManagerEnabled(string calldata walletManagerId) external view returns (bool);
function getWalletManager(string calldata walletManagerId) external view returns (IWalletManager);
// ERC721
function isNftBasketEnabled(string calldata basketId) external view returns (bool);
function getBasketManager(string calldata basketId) external view returns (IBasketManager);
/***********************************|
| Only NFT Creator |
|__________________________________*/
function setCreatorAnnuities(address contractAddress, uint256 tokenId, address creator, uint256 annuityPercent) external;
function setCreatorAnnuitiesRedirect(address contractAddress, uint256 tokenId, address creator, address receiver) external;
/***********************************|
| Only NFT Contract Owner |
|__________________________________*/
function setRequiredWalletManager(address contractAddress, string calldata walletManager) external;
function setRequiredBasketManager(address contractAddress, string calldata basketManager) external;
function setAssetTokenRestrictions(address contractAddress, bool restrictionsEnabled) external;
function setAllowedAssetToken(address contractAddress, address assetToken, bool isAllowed) external;
function setAssetTokenLimits(address contractAddress, address assetToken, uint256 depositMin, uint256 depositMax) external;
function setMaxNfts(address contractAddress, address nftTokenAddress, uint256 maxNfts) external;
/***********************************|
| Only Admin/DAO |
|__________________________________*/
function enableNftContracts(address[] calldata contracts) external;
function setPermsForCharge(address contractAddress, bool state) external;
function setPermsForBasket(address contractAddress, bool state) external;
function setPermsForTimelockAny(address contractAddress, bool state) external;
function setPermsForTimelockSelf(address contractAddress, bool state) external;
/***********************************|
| Particle Events |
|__________________________________*/
event DepositCapSet(address assetToken, uint256 depositCap);
event TempLockExpirySet(uint256 expiryBlocks);
event WalletManagerRegistered(string indexed walletManagerId, address indexed walletManager);
event BasketManagerRegistered(string indexed basketId, address indexed basketManager);
event RequiredWalletManagerSet(address indexed contractAddress, string walletManager);
event RequiredBasketManagerSet(address indexed contractAddress, string basketManager);
event AssetTokenRestrictionsSet(address indexed contractAddress, bool restrictionsEnabled);
event AllowedAssetTokenSet(address indexed contractAddress, address assetToken, bool isAllowed);
event AssetTokenLimitsSet(address indexed contractAddress, address assetToken, uint256 assetDepositMin, uint256 assetDepositMax);
event MaxNftsSet(address indexed contractAddress, address indexed nftTokenAddress, uint256 maxNfts);
event TokenCreatorConfigsSet(address indexed contractAddress, uint256 indexed tokenId, address indexed creatorAddress, uint256 annuityPercent);
event TokenCreatorAnnuitiesRedirected(address indexed contractAddress, uint256 indexed tokenId, address indexed redirectAddress);
event PermsSetForCharge(address indexed contractAddress, bool state);
event PermsSetForBasket(address indexed contractAddress, bool state);
event PermsSetForTimelockAny(address indexed contractAddress, bool state);
event PermsSetForTimelockSelf(address indexed contractAddress, bool state);
}
// SPDX-License-Identifier: MIT
// Bitwise.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity 0.6.12;
library Bitwise {
function negate(uint32 a) internal pure returns (uint32) {
return a ^ maxInt();
}
function shiftLeft(uint32 a, uint32 n) internal pure returns (uint32) {
return a * uint32(2) ** n;
}
function shiftRight(uint32 a, uint32 n) internal pure returns (uint32) {
return a / uint32(2) ** n;
}
function maxInt() internal pure returns (uint32) {
return uint32(-1);
}
// Get bit value at position
function hasBit(uint32 a, uint32 n) internal pure returns (bool) {
return a & shiftLeft(0x01, n) != 0;
}
// Set bit value at position
function setBit(uint32 a, uint32 n) internal pure returns (uint32) {
return a | shiftLeft(0x01, n);
}
// Set the bit into state "false"
function clearBit(uint32 a, uint32 n) internal pure returns (uint32) {
uint32 mask = negate(shiftLeft(0x01, n));
return a & mask;
}
}
// SPDX-License-Identifier: MIT
// TokenInfo.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity 0.6.12;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "../interfaces/IERC721Chargeable.sol";
library TokenInfo {
function getTokenUUID(address contractAddress, uint256 tokenId) internal pure virtual returns (uint256) {
return uint256(keccak256(abi.encodePacked(contractAddress, tokenId)));
}
function getTokenOwner(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.ownerOf(tokenId);
}
function getTokenCreator(address contractAddress, uint256 tokenId) internal view virtual returns (address) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
return tokenInterface.creatorOf(tokenId);
}
/// @dev Checks if an account is the Owner of an External NFT contract
/// @param contractAddress The Address to the Contract of the NFT to check
/// @param account The Address of the Account to check
/// @return True if the account owns the contract
function isContractOwner(address contractAddress, address account) internal view virtual returns (bool) {
address contractOwner = IERC721Chargeable(contractAddress).owner();
return contractOwner != address(0x0) && contractOwner == account;
}
/// @dev Checks if an account is the Creator of a Proton-based NFT
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT
function isTokenCreator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
return (sender == tokenCreator);
}
/// @dev Checks if an account is the Creator of a Proton-based NFT or the Contract itself
/// @param contractAddress The Address to the Contract of the Proton-based NFT to check
/// @param tokenId The Token ID of the Proton-based NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the creator of the Proton-based NFT or the Contract itself
function isTokenContractOrCreator(address contractAddress, uint256 tokenId, address creator, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenCreator = tokenInterface.creatorOf(tokenId);
if (sender == contractAddress && creator == tokenCreator) { return true; }
return (sender == tokenCreator);
}
/// @dev Checks if an account is the Owner or Operator of an External NFT
/// @param contractAddress The Address to the Contract of the External NFT to check
/// @param tokenId The Token ID of the External NFT to check
/// @param sender The Address of the Account to check
/// @return True if the account is the Owner or Operator of the External NFT
function isErc721OwnerOrOperator(address contractAddress, uint256 tokenId, address sender) internal view virtual returns (bool) {
IERC721Chargeable tokenInterface = IERC721Chargeable(contractAddress);
address tokenOwner = tokenInterface.ownerOf(tokenId);
return (sender == tokenOwner || tokenInterface.isApprovedForAll(tokenOwner, sender));
}
/**
* @dev Returns true if `account` is a contract.
* @dev Taken from OpenZeppelin library
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
* @dev Taken from OpenZeppelin library
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "TokenInfo: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "TokenInfo: unable to send value, recipient may have reverted");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "@opengsn/gsn/contracts/BaseRelayRecipient.sol";
contract RelayRecipient is BaseRelayRecipient {
function versionRecipient() external override view returns (string memory) {
return "1.0.0-beta.1/charged-particles.relay.recipient";
}
}
// SPDX-License-Identifier: MIT
// BlackholePrevention.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/**
* @notice Prevents ETH or Tokens from getting stuck in a contract by allowing
* the Owner/DAO to pull them out on behalf of a user
* This is only meant to contracts that are not expected to hold tokens, but do handle transferring them.
*/
contract BlackholePrevention {
using Address for address payable;
using SafeERC20 for IERC20;
event WithdrawStuckEther(address indexed receiver, uint256 amount);
event WithdrawStuckERC20(address indexed receiver, address indexed tokenAddress, uint256 amount);
event WithdrawStuckERC721(address indexed receiver, address indexed tokenAddress, uint256 indexed tokenId);
function _withdrawEther(address payable receiver, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (address(this).balance >= amount) {
receiver.sendValue(amount);
emit WithdrawStuckEther(receiver, amount);
}
}
function _withdrawERC20(address payable receiver, address tokenAddress, uint256 amount) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC20(tokenAddress).balanceOf(address(this)) >= amount) {
IERC20(tokenAddress).safeTransfer(receiver, amount);
emit WithdrawStuckERC20(receiver, tokenAddress, amount);
}
}
function _withdrawERC721(address payable receiver, address tokenAddress, uint256 tokenId) internal virtual {
require(receiver != address(0x0), "BHP:E-403");
if (IERC721(tokenAddress).ownerOf(tokenId) == address(this)) {
IERC721(tokenAddress).transferFrom(address(this), receiver, tokenId);
emit WithdrawStuckERC721(receiver, tokenAddress, tokenId);
}
}
}
// 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
// IWalletManager.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Particle Wallet Manager interface
* @dev The wallet-manager for underlying assets attached to Charged Particles
* @dev Manages the link between NFTs and their respective Smart-Wallets
*/
interface IWalletManager {
event ControllerSet(address indexed controller);
event PausedStateSet(bool isPaused);
event NewSmartWallet(address indexed contractAddress, uint256 indexed tokenId, address indexed smartWallet, address creator, uint256 annuityPct);
event WalletEnergized(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 assetAmount, uint256 yieldTokensAmount);
event WalletDischarged(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, uint256 creatorAmount, uint256 receiverAmount);
event WalletDischargedForCreator(address indexed contractAddress, uint256 indexed tokenId, address indexed assetToken, address creator, uint256 receiverAmount);
event WalletReleased(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address assetToken, uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
event WalletRewarded(address indexed contractAddress, uint256 indexed tokenId, address indexed receiver, address rewardsToken, uint256 rewardsAmount);
function isPaused() external view returns (bool);
function isReserveActive(address contractAddress, uint256 tokenId, address assetToken) external view returns (bool);
function getReserveInterestToken(address contractAddress, uint256 tokenId, address assetToken) external view returns (address);
function getTotal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256);
function getPrincipal(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256);
function getInterest(address contractAddress, uint256 tokenId, address assetToken) external returns (uint256 creatorInterest, uint256 ownerInterest);
function getRewards(address contractAddress, uint256 tokenId, address rewardToken) external returns (uint256);
function energize(address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount) external returns (uint256 yieldTokensAmount);
function discharge(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 creatorAmount, uint256 receiverAmount);
function dischargeAmountForCreator(address receiver, address contractAddress, uint256 tokenId, address creator, address assetToken, uint256 assetAmount) external returns (uint256 receiverAmount);
function release(address receiver, address contractAddress, uint256 tokenId, address assetToken, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
function releaseAmount(address receiver, address contractAddress, uint256 tokenId, address assetToken, uint256 assetAmount, address creatorRedirect) external returns (uint256 principalAmount, uint256 creatorAmount, uint256 receiverAmount);
function withdrawRewards(address receiver, address contractAddress, uint256 tokenId, address rewardsToken, uint256 rewardsAmount) external returns (uint256 amount);
function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function getWalletAddressById(address contractAddress, uint256 tokenId, address creator, uint256 annuityPct) external returns (address);
function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external;
function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external;
}
// SPDX-License-Identifier: MIT
// IBasketManager.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
/**
* @title Particle Basket Manager interface
* @dev The basket-manager for underlying assets attached to Charged Particles
* @dev Manages the link between NFTs and their respective Smart-Baskets
*/
interface IBasketManager {
event ControllerSet(address indexed controller);
event PausedStateSet(bool isPaused);
event NewSmartBasket(address indexed contractAddress, uint256 indexed tokenId, address indexed smartBasket);
event BasketAdd(address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId);
event BasketRemove(address indexed receiver, address indexed contractAddress, uint256 indexed tokenId, address basketTokenAddress, uint256 basketTokenId);
function isPaused() external view returns (bool);
function getTokenTotalCount(address contractAddress, uint256 tokenId) external view returns (uint256);
function getTokenCountByType(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (uint256);
function addToBasket(address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool);
function removeFromBasket(address receiver, address contractAddress, uint256 tokenId, address basketTokenAddress, uint256 basketTokenId) external returns (bool);
function executeForAccount(address contractAddress, uint256 tokenId, address externalAddress, uint256 ethValue, bytes memory encodedParams) external returns (bytes memory);
function getBasketAddressById(address contractAddress, uint256 tokenId) external returns (address);
function withdrawEther(address contractAddress, uint256 tokenId, address payable receiver, uint256 amount) external;
function withdrawERC20(address contractAddress, uint256 tokenId, address payable receiver, address tokenAddress, uint256 amount) external;
function withdrawERC721(address contractAddress, uint256 tokenId, address payable receiver, address nftTokenAddress, uint256 nftTokenId) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// IERC721Chargeable.sol -- Part of the Charged Particles Protocol
// Copyright (c) 2021 Firma Lux, Inc. <https://charged.fi>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
pragma solidity >=0.6.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
interface IERC721Chargeable is IERC165Upgradeable {
function owner() external view returns (address);
function creatorOf(uint256 tokenId) external view returns (address);
function balanceOf(address tokenOwner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address tokenOwner);
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 tokenOwner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier:MIT
// solhint-disable no-inline-assembly
pragma solidity ^0.6.2;
import "./interfaces/IRelayRecipient.sol";
/**
* A base contract to be inherited by any contract that want to receive relayed transactions
* A subclass must use "_msgSender()" instead of "msg.sender"
*/
abstract contract BaseRelayRecipient is IRelayRecipient {
/*
* Forwarder singleton we accept calls from
*/
address public trustedForwarder;
function isTrustedForwarder(address forwarder) public override view returns(bool) {
return forwarder == trustedForwarder;
}
/**
* return the sender of this call.
* if the call came through our trusted forwarder, return the original sender.
* otherwise, return `msg.sender`.
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal override virtual view returns (address payable ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// so we trust that the last bytes of msg.data are the verified sender address.
// extract sender address from the end of msg.data
assembly {
ret := shr(96,calldataload(sub(calldatasize(),20)))
}
} else {
return msg.sender;
}
}
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal override virtual view returns (bytes memory ret) {
if (msg.data.length >= 24 && isTrustedForwarder(msg.sender)) {
// At this point we know that the sender is a trusted forwarder,
// we copy the msg.data , except the last 20 bytes (and update the total length)
assembly {
let ptr := mload(0x40)
// copy only size-20 bytes
let size := sub(calldatasize(),20)
// structure RLP data as <offset> <length> <bytes>
mstore(ptr, 0x20)
mstore(add(ptr,32), size)
calldatacopy(add(ptr,64), 0, size)
return(ptr, add(size,64))
}
} else {
return msg.data;
}
}
}
// SPDX-License-Identifier:MIT
pragma solidity ^0.6.2;
/**
* a contract must implement this interface in order to support relayed transaction.
* It is better to inherit the BaseRelayRecipient as its implementation.
*/
abstract contract IRelayRecipient {
/**
* return if the forwarder is trusted to forward relayed transactions to us.
* the forwarder is required to verify the sender's signature, and verify
* the call is not a replay.
*/
function isTrustedForwarder(address forwarder) public virtual view returns(bool);
/**
* return the sender of this call.
* if the call came through our trusted forwarder, then the real sender is appended as the last 20 bytes
* of the msg.data.
* otherwise, return `msg.sender`
* should be used in the contract anywhere instead of msg.sender
*/
function _msgSender() internal virtual view returns (address payable);
/**
* return the msg.data of this call.
* if the call came through our trusted forwarder, then the real sender was appended as the last 20 bytes
* of the msg.data - so this method will strip those 20 bytes off.
* otherwise, return `msg.data`
* should be used in the contract instead of msg.data, where the difference matters (e.g. when explicitly
* signing or hashing the
*/
function _msgData() internal virtual view returns (bytes memory);
function versionRecipient() external virtual view returns (string memory);
}
// 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) {
// 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);
}
}
}
}
// 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.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transfered 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);
} | Asset Token Address => Max
| mapping (address => uint256) depositMax; | 458,456 | [
1,
6672,
3155,
5267,
516,
4238,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
443,
1724,
2747,
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
] |
./full_match/11155111/0xFb2c67ebE847bB170898bB1769859C95D0ee2EC5/sources/contracts/CrowdFunding.sol | Check if all is okay Returns the index of the most newly created campaign | function createCampaign(address _owner, string memory _title, string memory _desctription, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256) {
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _desctription;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns ++;
return numberOfCampaigns -1;
}
| 3,806,268 | [
1,
1564,
309,
777,
353,
21194,
2860,
326,
770,
434,
326,
4486,
10894,
2522,
8965,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
752,
13432,
12,
2867,
389,
8443,
16,
533,
3778,
389,
2649,
16,
533,
3778,
389,
5489,
299,
566,
375,
16,
2254,
5034,
389,
3299,
16,
2254,
5034,
389,
22097,
1369,
16,
533,
3778,
389,
2730,
13,
1071,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
17820,
2502,
8965,
273,
8965,
87,
63,
2696,
951,
13432,
87,
15533,
203,
203,
3639,
2583,
12,
14608,
18,
22097,
1369,
411,
1203,
18,
5508,
16,
315,
1986,
14096,
1410,
506,
279,
1509,
316,
326,
3563,
1199,
1769,
203,
203,
3639,
8965,
18,
8443,
273,
389,
8443,
31,
203,
3639,
8965,
18,
2649,
273,
389,
2649,
31,
203,
3639,
8965,
18,
3384,
273,
389,
5489,
299,
566,
375,
31,
203,
3639,
8965,
18,
3299,
273,
389,
3299,
31,
203,
3639,
8965,
18,
22097,
1369,
273,
389,
22097,
1369,
31,
203,
3639,
8965,
18,
8949,
10808,
329,
273,
374,
31,
203,
3639,
8965,
18,
2730,
273,
389,
2730,
31,
203,
203,
3639,
7922,
13432,
87,
965,
31,
203,
203,
203,
3639,
327,
7922,
13432,
87,
300,
21,
31,
7010,
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
] |
pragma solidity ^0.4.24;
contract EthGods {
// imported contracts
EthGodsName private eth_gods_name;
function set_eth_gods_name_contract_address(address eth_gods_name_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_name = EthGodsName(eth_gods_name_contract_address);
return true;
}
EthGodsDice private eth_gods_dice;
function set_eth_gods_dice_contract_address(address eth_gods_dice_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_dice = EthGodsDice(eth_gods_dice_contract_address);
return true;
}
// end of imported contracts
// start of database
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private contact_email = "[email protected]";
string private official_url = "swarm-gateways.net/bzz:/ethgods.eth";
address private admin; // public when testing
address private controller1 = 0xcA5A9Db0EF9a0Bf5C38Fc86fdE6CB897d9d86adD; // controller can change admin at once;
address private controller2 = 0x8396D94046a099113E5fe5CBad7eC95e96c2B796; // controller can change admin at once;
address private v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
uint private block_hash_duration = 255; // can't get block hash, after 256 blocks, adjustable
// god
struct god {
uint god_id;
uint level;
uint exp;
uint pet_type;// 12 animals or zodiacs
uint pet_level;
uint listed; // 0 not a god, 1 - ... rank_score in god list
uint invite_price;
uint blessing_player_id;
bool hosted_pray; // auto waitlist, when enlisted. others can invite, once hosted pray
uint bid_eth; // bid to host pray
uint credit; // gained from the amulet invitation spending of invited fellows
uint count_amulets_generated;
uint first_amulet_generated;
uint count_amulets_at_hand;
uint count_amulets_selling;
uint amulets_start_id;
uint amulets_end_id;
uint count_token_orders;
uint first_active_token_order;
uint allowed_block; // allow another account to use my egst
uint block_number; // for pray
bytes32 gene;
bool gene_created;
bytes32 pray_hash; //hash created for each pray
uint inviter_id; // who invited this fellow to this world
uint count_gods_invited; // gods invited to this game by this god.
}
uint private count_gods = 0; // Used when generating id for a new player,
mapping(address => god) private gods; // everyone is a god
mapping(uint => address) private gods_address; // gods' address => god_id
uint [] private listed_gods; // id of listed gods
uint private max_listed_gods = 10000; // adjustable
uint private initial_invite_price = 0.02 ether; // grows with each invitation for this god
uint private invite_price_increase = 0.02 ether; // grows by this amount with each invitation
uint private max_invite_price = 1000 ether; // adjustable
uint private max_extra_eth = 0.001 ether; // adjustable
uint private list_level = 10; // start from level 10
uint private max_gas_price = 100000000000; // 100 gwei for invite and pray, adjustable
// amulet
struct amulet {
uint god_id;
address owner;
uint level;
uint bound_start_block;// can't sell, if just got
// bool selling;
uint start_selling_block; // can't bind & use in pk, if selling
uint price; // set to 0, when withdraw from selling or bought
// uint order_id; // should be 0, if not selling
}
uint private count_amulets = 0;
mapping(uint => amulet) private amulets; // public when testing
uint private bound_duration = 9000; // once bought, wait a while before sell it again, adjustable
uint private order_duration = 20000; // valid for about 3 days, then not to show to public in selling amulets/token orders, but still show in my_selling amulets/token orders. adjustable
// pray
address private pray_host_god; // public when testing
bool private pray_reward_top100; // if hosted by new god, reward top 100 gods egst
uint private pray_start_block; // public when testing
bool private rewarded_pray_winners = false;
uint private count_hosted_gods; // gods hosted pray (event started). If less than bidding gods, there are new gods waiting to host pray,
mapping (uint => address) private bidding_gods; // every listed god and bid to host pray
uint private initializer_reward = 36; // reward the god who burned gas to send pray rewards to community, adjustable
mapping(uint => uint) private max_winners; // max winners for each prize
uint private min_pray_interval = 2000; // 2000, 36 in CBT, 2 in dev, adjustable
uint private min_pray_duration = 6000; // 6000, 600 in CBT, 60 in dev, adjustable
uint private max_pray_duration = 9000; // 9000, 900 in CBT, 90 in dev, adjustable
uint private count_waiting_prayers;
mapping (uint => address) private waiting_prayers; // uint is waiting sequence
uint private waiting_prayer_index = 1; // waiting sequence of the prayer ready to draw lot
mapping(uint => uint) private pk_positions; // public when testing
mapping(uint => uint) private count_listed_winners; // count for 5 prizes, public in testing
mapping (uint => mapping(uint => address)) private listed_winners; // winners for 5 prizes
bool private reEntrancyMutex = false; // for sendnig eth to msg.sender
uint private pray_egses = 0; // 10% from reward pool to top 3 winners in each round of pray events
uint private pray_egst = 0; // 10% from reward pool to 3rd & 4th prize winners in each round of pray events
mapping(address => uint) egses_balances;
// eth_gods_token (EGST)
string public name = "EthGodsToken";
string public symbol = "EGST";
uint8 public decimals = 18; //same as ethereum
uint private _totalSupply;
mapping(address => uint) balances; // bought or gained from pray or revenue share
mapping(address => mapping(address => uint)) allowed;
uint private allowed_use_CD = 20; // if used allowed amount, have to wait a while before approve new allowed amount again, prevent cheating, adjustable
struct token_order {
uint id;
uint start_selling_block;
address seller;
uint unit_price;
uint egst_amount;
}
uint private count_token_orders = 0;
mapping (uint => token_order) token_orders;
uint private first_active_token_order = 0;
uint private min_unit_price = 20; // 1 egst min value is 0.0002 ether, adjustable
uint private max_unit_price = 200; // 1 egst max value is 0.002 ether, adjustable
uint private max_egst_amount = 1000000 ether; // for create_token_order, adjustable
uint private min_egst_amount = 0.00001 ether; // for create_token_order, adjustable
//logs
uint private count_rounds = 0;
struct winner_log { // win a prize and if pk
uint god_block_number;
bytes32 block_hash;
address prayer;
address previous_winner;
uint prize;
bool pk_result;
}
mapping (uint => uint) private count_rounds_winner_logs;
mapping(uint => mapping(uint => winner_log)) private winner_logs;
struct change_log {
uint block_number;
uint asset_type; // 1 egst, 2 eth_surplus
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token,
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward
uint reason; // > 10 is buy token unit_price
uint change_amount;
uint after_amount;
address _from;
address _to;
}
mapping (uint => uint) private count_rounds_change_logs;
mapping(uint => mapping(uint => change_log)) private change_logs;
// end of database
// start of constructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
create_god(admin, 0);
create_god(v_god, 0);
gods[v_god].level = 10;
enlist_god(v_god);
max_winners[1] = 1; // 1
max_winners[2] = 2; // 2
max_winners[3] = 8; // 8
max_winners[4] = 16; // 16
max_winners[5] = 100; // 100
_totalSupply = 6000000 ether;
pray_egst = 1000 ether;
balances[admin] = sub(_totalSupply, pray_egst);
initialize_pray();
}
// destruct for testing contracts. can't destruct since round 3
function finalize() public {
require(msg.sender == admin && count_rounds <= 3);
selfdestruct(admin);
}
function () public payable {
revert ();
}
// end of constructor
//start of contract information & administration
function get_controller () public view returns (address, address){
require (msg.sender == admin || msg.sender == controller1 || msg.sender == controller2);
return (controller1, controller2);
}
function set_controller (uint controller_index, address new_controller_address) public returns (bool){
if (controller_index == 1){
require(msg.sender == controller2);
controller1 = new_controller_address;
} else {
require(msg.sender == controller1);
controller2 = new_controller_address;
}
return true;
}
function set_admin (address new_admin_address) public returns (bool) {
require (msg.sender == controller1 || msg.sender == controller2);
// admin don't have game attributes, such as level'
// no need to transfer egses and egst to new_admin_address
delete gods[admin];
admin = new_admin_address;
gods_address[0] = admin;
gods[admin].god_id = 0;
return true;
}
// update system parameters
function set_parameters (uint parameter_type, uint new_parameter) public returns (bool){
require (msg.sender == admin);
if (parameter_type == 1) {
max_pray_duration = new_parameter;
} else if (parameter_type == 2) {
min_pray_duration = new_parameter;
} else if (parameter_type == 3) {
block_hash_duration = new_parameter;
} else if (parameter_type == 4) {
min_pray_interval = new_parameter;
} else if (parameter_type == 5) {
order_duration = new_parameter;
} else if (parameter_type == 6) {
bound_duration = new_parameter;
} else if (parameter_type == 7) {
initializer_reward = new_parameter;
} else if (parameter_type == 8) {
allowed_use_CD = new_parameter;
} else if (parameter_type == 9) {
min_unit_price = new_parameter;
} else if (parameter_type == 10) {
max_unit_price = new_parameter;
} else if (parameter_type == 11) {
max_listed_gods = new_parameter;
} else if (parameter_type == 12) {
max_gas_price = new_parameter;
} else if (parameter_type == 13) {
max_invite_price = new_parameter;
} else if (parameter_type == 14) {
min_egst_amount = new_parameter;
} else if (parameter_type == 15) {
max_egst_amount = new_parameter;
} else if (parameter_type == 16) {
max_extra_eth = new_parameter;
}
return true;
}
function set_strings (uint string_type, string new_string) public returns (bool){
require (msg.sender == admin);
if (string_type == 1){
official_url = new_string;
} else if (string_type == 2){
name = new_string; // egst name
} else if (string_type == 3){
symbol = new_string; // egst symbol
}
return true;
}
// for basic information to show to players, and to update parameter in sub-contracts
function query_contract () public view returns(uint, uint, address, uint, string, uint, uint){
return (count_gods,
listed_gods.length,
admin,
block_hash_duration,
official_url,
bound_duration,
min_pray_interval
);
}
function query_uints () public view returns (uint[7] uints){
uints[0] = max_invite_price;
uints[1] = list_level;
uints[2] = max_pray_duration;
uints[3] = min_pray_duration;
uints[4] = initializer_reward;
uints[5] = min_unit_price;
uints[6] = max_unit_price;
return uints;
}
function query_uints2 () public view returns (uint[6] uints){
uints[0] = allowed_use_CD;
uints[1] = max_listed_gods;
uints[2] = max_gas_price;
uints[3] = min_egst_amount;
uints[4] = max_egst_amount;
uints[5] = max_extra_eth;
return uints;
}
//end of contract information & administration
// god related functions: register, create_god, upgrade_pet, add_exp, burn_gas, invite, enlist
// if a new player comes when a round just completed, the new player may not want to initialize the next round
function register_god (uint inviter_id) public returns (uint) {
return create_god(msg.sender, inviter_id);
}
function create_god (address god_address, uint inviter_id) private returns(uint god_id){ // created by the contract // public when testing
// check if the god is already created
if (gods[god_address].credit == 0) { // create admin as god[0]
gods[god_address].credit = 1; // give 1 credit, so we know this address has a god
god_id = count_gods; // 1st god's id is admin 0
count_gods = add(count_gods, 1) ;
gods_address[god_id] = god_address;
gods[god_address].god_id = god_id;
if (god_id > 0){ // not admin
add_exp(god_address, 100);
set_inviter(inviter_id);
}
return god_id;
}
}
function set_inviter (uint inviter_id) public returns (bool){
if (inviter_id > 0 && gods_address[inviter_id] != address(0)
&& gods[msg.sender].inviter_id == 0
&& gods[gods_address[inviter_id]].inviter_id != gods[msg.sender].god_id){
gods[msg.sender].inviter_id = inviter_id;
address inviter_address = gods_address[inviter_id];
gods[inviter_address].count_gods_invited = add(gods[inviter_address].count_gods_invited, 1);
return true;
}
}
function add_exp (address god_address, uint exp_up) private returns(uint new_level, uint new_exp) { // public when testing
if (god_address == admin){
return (0,0);
}
if (gods[god_address].god_id == 0){
uint inviter_id = gods[god_address].inviter_id;
create_god(god_address, inviter_id);
}
new_exp = add(gods[god_address].exp, exp_up);
uint current_god_level = gods[god_address].level;
uint level_up_exp;
new_level = current_god_level;
for (uint i=0;i<10;i++){ // if still have extra exp, level up next time
if (current_god_level < 99){
level_up_exp = mul(10, add(new_level, 1));
} else {
level_up_exp = 1000;
}
if (new_exp >= level_up_exp){
new_exp = sub(new_exp, level_up_exp);
new_level = add(new_level, 1);
} else {
break;
}
}
gods[god_address].exp = new_exp;
if(new_level > current_god_level) {
gods[god_address].level = new_level;
if (gods[god_address].listed > 0) {
if (listed_gods.length > 1) {
sort_gods(gods[god_address].god_id);
}
} else if (new_level >= list_level && listed_gods.length < max_listed_gods) {
enlist_god(god_address);
}
}
return (new_level, new_exp);
}
function enlist_god (address god_address) private returns (uint) { // public when testing
require(gods[god_address].level >= list_level && god_address != admin);
// if the god is not listed yet, enlist and add level requirement for the next enlist
if (gods[god_address].listed == 0) {
uint god_id = gods[god_address].god_id;
if (god_id == 0){
god_id = create_god(god_address, 0); // get a god_id and set inviter as v god
}
gods[god_address].listed = listed_gods.push(god_id); // start from 1, 0 is not listed
gods[god_address].invite_price = initial_invite_price;
list_level = add(list_level, 1);
bidding_gods[listed_gods.length] = god_address;
}
return list_level;
}
function sort_gods_admin(uint god_id) public returns (bool){
require (msg.sender == admin);
sort_gods(god_id);
return true;
}
// when a listed god level up and is not top 1 of the list, compare power with higher god, if higher than the higher god, swap position
function sort_gods (uint god_id) private returns (uint){
require (god_id > 0);
uint list_length = listed_gods.length;
if (list_length > 1) {
address god_address = gods_address[god_id];
uint this_god_listed = gods[god_address].listed;
if (this_god_listed < list_length) {
uint higher_god_listed = add(this_god_listed, 1);
uint higher_god_id = listed_gods[sub(higher_god_listed, 1)];
address higher_god = gods_address[higher_god_id];
if(gods[god_address].level > gods[higher_god].level
|| (gods[god_address].level == gods[higher_god].level
&& gods[god_address].exp > gods[higher_god].exp)){
listed_gods[sub(this_god_listed, 1)] = higher_god_id;
listed_gods[sub(higher_god_listed, 1)] = god_id;
gods[higher_god].listed = this_god_listed;
gods[god_address].listed = higher_god_listed;
}
}
}
return gods[god_address].listed;
}
function burn_gas (uint god_id) public returns (uint god_new_level, uint god_new_exp) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].listed > 0);
add_exp(god_address, 1);
add_exp(msg.sender, 1);
return (gods[god_address].level, gods[god_address].exp); // return bool, if out of gas
}
function invite (uint god_id) public payable returns (uint new_invite_price) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].hosted_pray == true
&& tx.gasprice <= max_gas_price
);
uint invite_price = gods[god_address].invite_price;
require(msg.value >= invite_price);
if (gods[god_address].invite_price < max_invite_price) {
gods[god_address].invite_price = add(invite_price, invite_price_increase);
}
uint exp_up = div(invite_price, (10 ** 15)); // 1000 exp for each eth
add_exp(god_address, exp_up);
add_exp(msg.sender, exp_up);
//generate a new amulet of this god for the inviter
count_amulets ++;
amulets[count_amulets].god_id = god_id;
amulets[count_amulets].owner = msg.sender;
gods[god_address].count_amulets_generated = add(gods[god_address].count_amulets_generated, 1);
if (gods[god_address].count_amulets_generated == 1){
gods[god_address].first_amulet_generated = count_amulets;
}
gods[msg.sender].count_amulets_at_hand = add(gods[msg.sender].count_amulets_at_hand, 1);
update_amulets_count(msg.sender, count_amulets, true);
// invite_price to egses: 60% to pray_egses, 20% to god, changed
// pray_egses = add(pray_egses, div(mul(60, invite_price), 100));
// egses_from_contract(gods_address[god_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited
// reduce reward pool share from 60 to 50%, reduce god reward from 20% to 10%
// add 20% share to blessing player (the last player invited this god)
pray_egses = add(pray_egses, div(mul(50, invite_price), 100));
egses_from_contract(god_address, div(mul(10, invite_price), 100), 2); //2 reward god for being invited
egses_from_contract(gods_address[gods[god_address].blessing_player_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited, no need to check if blessing player id is > 0
gods[god_address].blessing_player_id = gods[msg.sender].god_id;
reward_inviter(msg.sender, invite_price);
emit invited_god (msg.sender, god_id);
return gods[god_address].invite_price;
}
event invited_god (address msg_sender, uint god_id);
function reward_inviter (address inviter_address, uint invite_price) private returns (bool){
// the fellow spending eth also get credit and share
uint previous_share = 0;
uint inviter_share = 0;
uint share_diff;
// uint invite_credit = div(invite_price, 10 ** 15);
for (uint i = 0; i < 9; i++){ // max trace 9 layers of inviter
if (inviter_address != address(0) && inviter_address != admin){ // admin doesn't get reward or credit
share_diff = 0;
// gods[inviter_address].credit = add(gods[inviter_address].credit, invite_credit);
gods[inviter_address].credit = add(gods[inviter_address].credit, invite_price);
inviter_share = get_vip_level(inviter_address);
if (inviter_share > previous_share) {
share_diff = sub(inviter_share, previous_share);
if (share_diff > 18) {
share_diff = 18;
}
previous_share = inviter_share;
}
if (share_diff > 0) {
egses_from_contract(inviter_address, div(mul(share_diff, invite_price), 100), 3); // 3 inviter_reward
}
inviter_address = gods_address[gods[inviter_address].inviter_id]; // get the address of inviter's inviter'
} else{
break;
}
}
// invite_price to egses: sub(20%, previous_share) to admin
share_diff = sub(20, inviter_share);
egses_from_contract(admin, div(mul(share_diff, invite_price), 100), 2); // remaining goes to admin, 2 god_reward for being invited
return true;
}
function upgrade_pet () public returns(bool){
//use egst to level up pet;
uint egst_cost = mul(add(gods[msg.sender].pet_level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 6);// 6 upgrade_pet
gods[msg.sender].pet_level = add(gods[msg.sender].pet_level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
emit upgradeAmulet(msg.sender, 0, gods[msg.sender].pet_level);
return true;
}
event upgradeAmulet (address owner, uint amulet_id, uint new_level);
function set_pet_type (uint new_type) public returns (bool){
if (gods[msg.sender].pet_type != new_type) {
gods[msg.sender].pet_type = new_type;
return true;
}
}
function get_vip_level (address god_address) public view returns (uint vip_level){
uint inviter_credit = gods[god_address].credit;
if (inviter_credit > 500 ether){
vip_level = 18;
} else if (inviter_credit > 200 ether){
vip_level = 15;
} else if (inviter_credit > 100 ether){
vip_level = 12;
} else if (inviter_credit > 50 ether){
vip_level = 10;
} else if (inviter_credit > 20 ether){
vip_level = 8;
} else if (inviter_credit > 10 ether){
vip_level = 6;
} else if (inviter_credit > 5 ether){
vip_level = 5;
} else if (inviter_credit > 2 ether){
vip_level = 4;
} else if (inviter_credit > 1 ether){
vip_level = 3;
} else if (inviter_credit > 0.5 ether){
vip_level = 2;
} else {
vip_level = 1;
}
return vip_level;
}
// view god's information
function get_god_id (address god_address) public view returns (uint god_id){
return gods[god_address].god_id;
}
function get_god_address(uint god_id) public view returns (address){
return gods_address[god_id];
}
function get_god (uint god_id) public view returns(uint, string, uint, uint, uint, uint, uint) {
address god_address = gods_address[god_id];
string memory god_name;
god_name = eth_gods_name.get_god_name(god_address);
if (bytes(god_name).length == 0){
god_name = "Unknown";
}
return (gods[god_address].god_id,
god_name,
gods[god_address].level,
gods[god_address].exp,
gods[god_address].invite_price,
gods[god_address].listed,
gods[god_address].blessing_player_id
);
}
function get_god_info (address god_address) public view returns (uint, bytes32, bool, uint, uint, uint, bytes32){
return (gods[god_address].block_number,
gods[god_address].gene,
gods[god_address].gene_created,
gods[god_address].pet_type,
gods[god_address].pet_level,
gods[god_address].bid_eth,
gods[god_address].pray_hash
);
}
function get_god_hosted_pray (uint god_id) public view returns (bool){
return gods[gods_address[god_id]].hosted_pray;
}
function get_my_info () public view returns(uint, uint, uint, uint, uint, uint, uint) { //private information
return (gods[msg.sender].god_id,
egses_balances[msg.sender], //egses
balances[msg.sender], //egst
get_vip_level(msg.sender),
gods[msg.sender].credit, // inviter_credit
gods[msg.sender].inviter_id,
gods[msg.sender].count_gods_invited
);
}
function get_listed_gods (uint page_number) public view returns (uint[]){
uint count_listed_gods = listed_gods.length;
require(count_listed_gods <= mul(page_number, 20));
uint[] memory tempArray = new uint[] (20);
if (page_number < 1) {
page_number = 1;
}
for (uint i = 0; i < 20; i++){
if(count_listed_gods > add(i, mul(20, sub(page_number, 1)))) {
tempArray[i] = listed_gods[sub(sub(sub(count_listed_gods, i), 1), mul(20, sub(page_number, 1)))];
} else {
break;
}
}
return tempArray;
}
// amulets
function upgrade_amulet (uint amulet_id) public returns(uint){
require(amulets[amulet_id].owner == msg.sender);
uint egst_cost = mul(add(amulets[amulet_id].level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 7);// reason 7, upgrade_amulet
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
amulets[amulet_id].level = add(amulets[amulet_id].level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
emit upgradeAmulet(msg.sender, amulet_id, amulets[amulet_id].level);
return amulets[amulet_id].level;
}
function create_amulet_order (uint amulet_id, uint price) public returns (uint) {
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block == 0
&& add(amulets[amulet_id].bound_start_block, bound_duration) < block.number
&& price > 0);
amulets[amulet_id].start_selling_block = block.number;
amulets[amulet_id].price = price;
gods[msg.sender].count_amulets_at_hand = sub(gods[msg.sender].count_amulets_at_hand, 1);
gods[msg.sender].count_amulets_selling = add(gods[msg.sender].count_amulets_selling, 1);
return gods[msg.sender].count_amulets_selling;
}
function buy_amulet (uint amulet_id) public payable returns (bool) {
uint price = amulets[amulet_id].price;
require(msg.value >= price && msg.value < add(price, max_extra_eth)
&& amulets[amulet_id].start_selling_block > 0
&& amulets[amulet_id].owner != msg.sender
&& price > 0);
address seller = amulets[amulet_id].owner;
amulets[amulet_id].owner = msg.sender;
amulets[amulet_id].bound_start_block = block.number;
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
update_amulets_count(msg.sender, amulet_id, true);
gods[seller].count_amulets_selling--;
update_amulets_count(seller, amulet_id, false);
egses_from_contract(seller, price, 6); // 6 sell amulet
return true;
}
function withdraw_amulet_order (uint amulet_id) public returns (uint){
// an amulet can only have one order_id, so withdraw amulet_id instead of withdraw order_id, since only amulet_id is shown in amulets_at_hand
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block > 0);
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
gods[msg.sender].count_amulets_selling--;
return gods[msg.sender].count_amulets_selling;
}
function update_amulets_count (address god_address, uint amulet_id, bool obtained) private returns (uint){
if (obtained == true){
if (amulet_id < gods[god_address].amulets_start_id) {
gods[god_address].amulets_start_id = amulet_id;
}
} else {
if (amulet_id == gods[god_address].amulets_start_id){
for (uint i = amulet_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && i > amulet_id){
gods[god_address].amulets_start_id = i;
break;
}
}
}
}
return gods[god_address].amulets_start_id;
}
function get_amulets_generated (uint god_id) public view returns (uint[]) {
address god_address = gods_address[god_id];
uint count_amulets_generated = gods[god_address].count_amulets_generated;
uint [] memory temp_list = new uint[](count_amulets_generated);
uint count_elements = 0;
for (uint i = gods[god_address].first_amulet_generated; i <= count_amulets; i++){
if (amulets[i].god_id == god_id){
temp_list [count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_generated){
break;
}
}
}
return temp_list;
}
function get_amulets_at_hand (address god_address) public view returns (uint[]) {
uint count_amulets_at_hand = gods[god_address].count_amulets_at_hand;
uint [] memory temp_list = new uint[] (count_amulets_at_hand);
uint count_elements = 0;
for (uint i = gods[god_address].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_at_hand){
break;
}
}
}
return temp_list;
}
function get_my_amulets_selling () public view returns (uint[]){
uint count_amulets_selling = gods[msg.sender].count_amulets_selling;
uint [] memory temp_list = new uint[] (count_amulets_selling);
uint count_elements = 0;
for (uint i = gods[msg.sender].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == msg.sender
&& amulets[i].start_selling_block > 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_selling){
break;
}
}
}
return temp_list;
}
// to calculate how many pages
function get_amulet_orders_overview () public view returns(uint){
uint count_amulets_selling = 0;
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
return count_amulets_selling; // to show page numbers when getting amulet_orders
}
function get_amulet_orders (uint page_number) public view returns (uint[]){
uint[] memory temp_list = new uint[] (20);
uint count_amulets_selling = 0;
uint count_list_elements = 0;
if ((page_number < 1)
|| count_amulets <= 20) {
page_number = 1; // chose a page out of range
}
uint start_amulets_count = mul(sub(page_number, 1), 20);
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
if (count_amulets_selling <= start_amulets_count) {
count_amulets_selling ++;
}
if (count_amulets_selling > start_amulets_count){
temp_list[count_list_elements] = i;
count_list_elements ++;
if (count_list_elements >= 20){
break;
}
}
}
}
return temp_list;
}
function get_amulet (uint amulet_id) public view returns(address, string, uint, uint, uint, uint, uint){
uint god_id = amulets[amulet_id].god_id;
// address god_address = gods_address[god_id];
string memory god_name = eth_gods_name.get_god_name(gods_address[god_id]);
uint god_level = gods[gods_address[god_id]].level;
uint amulet_level = amulets[amulet_id].level;
uint start_selling_block = amulets[amulet_id].start_selling_block;
uint price = amulets[amulet_id].price;
return(amulets[amulet_id].owner,
god_name,
god_id,
god_level,
amulet_level,
start_selling_block,
price
);
}
function get_amulet2 (uint amulet_id) public view returns(uint){
return amulets[amulet_id].bound_start_block;
}
// end of amulet
// start of pray
function admin_deposit (uint egst_amount) public payable returns (bool) {
require (msg.sender == admin);
if (msg.value > 0){
pray_egses = add(pray_egses, msg.value);
egses_from_contract(admin, msg.value, 4); // 4 admin_deposit to reward_pool
}
if (egst_amount > 0){
pray_egst = add(pray_egst, egst_amount);
egst_to_contract(admin, egst_amount, 4); // 4 admin_deposit to reward_pool
}
return true;
}
function initialize_pray () private returns (bool){
if (pray_start_block > 0) {
require (check_event_completed() == true
&& rewarded_pray_winners == true);
}
count_rounds = add(count_rounds, 1);
count_rounds_winner_logs[count_rounds] = 0;
pray_start_block = block.number;
rewarded_pray_winners = false;
for (uint i = 1; i <= 5; i++){
pk_positions[i] = max_winners[i]; // pk start from the last slot
count_listed_winners[i] = 0;
}
if (listed_gods.length > count_hosted_gods) {
// a new god's turn
count_hosted_gods = add(count_hosted_gods, 1);
pray_host_god = bidding_gods[count_hosted_gods];
gods[pray_host_god].hosted_pray = true;
pray_reward_top100 = true;
} else {
//choose highest bidder
(uint highest_bid, address highest_bidder) = compare_bid_eth();
gods[highest_bidder].bid_eth = 0;
pray_host_god = highest_bidder;
pray_egses = add(pray_egses, highest_bid);
pray_reward_top100 = false;
}
return true;
}
function bid_host () public payable returns (bool) {
require (msg.value > 0 && gods[msg.sender].listed > 0);
gods[msg.sender].bid_eth = add (gods[msg.sender].bid_eth, msg.value);
return true;
}
function withdraw_bid () public returns (bool) {
require(gods[msg.sender].bid_eth > 0);
gods[msg.sender].bid_eth = 0;
egses_from_contract(msg.sender, gods[msg.sender].bid_eth, 8); // 8 withdraw bid
return true;
}
// if browser web3 didn't get god's credit, use pray_create in the pray button to create god_id first
function pray_create (uint inviter_id) public returns (bool) {
// when create a new god, set credit as 1, so credit <= 0 means god_id not created yet
create_god(msg.sender, inviter_id);
pray();
}
// if browser web3 got god's credit, use pray in the pray button
function pray () public returns (bool){
require (add(gods[msg.sender].block_number, min_pray_interval) < block.number
&& tx.gasprice <= max_gas_price
&& check_event_completed() == false);
if (waiting_prayer_index <= count_waiting_prayers) {
address waiting_prayer = waiting_prayers[waiting_prayer_index];
uint god_block_number = gods[waiting_prayer].block_number;
bytes32 block_hash;
if ((add(god_block_number, 1)) < block.number) {// can only get previous block hash
if (add(god_block_number, block_hash_duration) < block.number) {// make sure this god has a valid block_number to generate block hash
gods[waiting_prayer].block_number = block.number; // refresh this god's expired block_id
// delete waiting_prayers[waiting_prayer_index];
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = waiting_prayer;
} else {// draw lottery and/or create gene for the waiting prayer
block_hash = keccak256(abi.encodePacked(blockhash(add(god_block_number, 1))));
if(gods[waiting_prayer].gene_created == false){
gods[waiting_prayer].gene = block_hash;
gods[waiting_prayer].gene_created = true;
}
gods[waiting_prayer].pray_hash = block_hash;
uint dice_result = eth_gods_dice.throw_dice (block_hash)[0];
if (dice_result >= 1 && dice_result <= 5){
set_winner(dice_result, waiting_prayer, block_hash, god_block_number);
}
}
waiting_prayer_index = add(waiting_prayer_index, 1);
}
}
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = msg.sender;
gods[msg.sender].block_number = block.number;
add_exp(msg.sender, 1);
add_exp(pray_host_god, 1);
return true;
}
function set_winner (uint prize, address waiting_prayer, bytes32 block_hash, uint god_block_number) private returns (uint){
count_rounds_winner_logs[count_rounds] = add(count_rounds_winner_logs[count_rounds], 1);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].god_block_number = god_block_number;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].block_hash = block_hash;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prayer = waiting_prayer;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prize = prize;
if (count_listed_winners[prize] >= max_winners[prize]){ // winner_list maxed, so the new prayer challenge previous winners
uint pk_position = pk_positions[prize];
address previous_winner = listed_winners[prize][pk_position];
bool pk_result = pk(waiting_prayer, previous_winner, block_hash);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].pk_result = pk_result;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].previous_winner = previous_winner;
if (pk_result == true) {
listed_winners[prize][pk_position] = waiting_prayer; // attacker defeat defender
}
if (prize > 1) { // no need to change pk_pos for champion
if (pk_positions[prize] > 1){
pk_positions[prize] = sub(pk_positions[prize], 1);
} else {
pk_positions[prize] = max_winners[prize];
}
}
} else {
count_listed_winners[prize] = add(count_listed_winners[prize], 1);
listed_winners[prize][count_listed_winners[prize]] = waiting_prayer;
}
return count_listed_winners[prize];
}
function reward_pray_winners () public returns (bool){
require (check_event_completed() == true);
uint this_reward_egses;
uint reward_pool_egses = div(pray_egses, 10);
pray_egses = sub(pray_egses, reward_pool_egses);
uint this_reward_egst;
uint reward_pool_egst = div(pray_egst, 10);
pray_egst = sub(pray_egst, reward_pool_egst); // reduce sum for less calculation
egst_from_contract(pray_host_god, mul(div(reward_pool_egst, 100), 60), 1); // 1 pray_reward for hosting event
for (uint i = 1; i<=5; i++){
this_reward_egses = 0;
this_reward_egst = 0;
if (i == 1) {
this_reward_egses = mul(div(reward_pool_egses, 100), 60);
} else if (i == 2){
this_reward_egses = mul(div(reward_pool_egses, 100), 20);
} else if (i == 3){
this_reward_egst = mul(div(reward_pool_egst, 100), 3);
} else if (i == 4){
this_reward_egst = div(reward_pool_egst, 100);
}
for (uint reward_i = 1; reward_i <= count_listed_winners[i]; reward_i++){
address rewarding_winner = listed_winners[i][reward_i];
if (this_reward_egses > 0 ) {
egses_from_contract(rewarding_winner, this_reward_egses, 1); // 1 pray_reward
} else if (this_reward_egst > 0) {
egst_from_contract(rewarding_winner, this_reward_egst, 1); // 1 pray_reward
}
add_exp(rewarding_winner, 6);
}
}
if(pray_reward_top100 == true) {
reward_top_gods();
}
// a small gift of exp & egst to the god who burned gas to send rewards to the community
egst_from_contract(msg.sender, mul(initializer_reward, 1 ether), 1); // 1 pray_reward
_totalSupply = add(_totalSupply, mul(initializer_reward, 1 ether));
add_exp(msg.sender, initializer_reward);
rewarded_pray_winners = true;
initialize_pray();
return true;
}
// more listed gods, more reward to the top gods, highest reward 600 egst
function reward_top_gods () private returns (bool){ // public when testing
uint count_listed_gods = listed_gods.length;
uint last_god_index;
if (count_listed_gods > 100) {
last_god_index = sub(count_listed_gods, 100);
} else {
last_god_index = 0;
}
uint reward_egst = 0;
uint base_reward = 6 ether;
if (count_rounds == 6){
base_reward = mul(base_reward, 6);
}
for (uint i = last_god_index; i < count_listed_gods; i++) {
reward_egst = mul(base_reward, sub(add(i, 1), last_god_index));
egst_from_contract(gods_address[listed_gods[i]], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
if (gods[gods_address[listed_gods[i]]].blessing_player_id > 0){
egst_from_contract(gods_address[gods[gods_address[listed_gods[i]]].blessing_player_id], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
}
}
return true;
}
function compare_bid_eth () private view returns (uint, address) {
uint highest_bid = 0;
address highest_bidder = v_god; // if no one bid, v god host this event
for (uint j = 1; j <= listed_gods.length; j++){
if (gods[bidding_gods[j]].bid_eth > highest_bid){
highest_bid = gods[bidding_gods[j]].bid_eth;
highest_bidder = bidding_gods[j];
}
}
return (highest_bid, highest_bidder);
}
function check_event_completed () public view returns (bool){
// check min and max pray_event duration
if (add(pray_start_block, max_pray_duration) > block.number){
if (add(pray_start_block, min_pray_duration) < block.number){
for (uint i = 1; i <= 5; i++){
if(count_listed_winners[i] < max_winners[i]){
return false;
}
}
return true;
} else {
return false;
}
} else {
return true;
}
}
function pk (address attacker, address defender, bytes32 block_hash) public view returns (bool pk_result){// make it public, view only, other contract may use it
(uint attacker_sum_god_levels, uint attacker_sum_amulet_levels) = get_sum_levels_pk(attacker);
(uint defender_sum_god_levels, uint defender_sum_amulet_levels) = get_sum_levels_pk(defender);
pk_result = eth_gods_dice.pk(block_hash, attacker_sum_god_levels, attacker_sum_amulet_levels, defender_sum_god_levels, defender_sum_amulet_levels);
return pk_result;
}
function get_sum_levels_pk (address god_address) public view returns (uint sum_gods_level, uint sum_amulets_level){
sum_gods_level = gods[god_address].level;
sum_amulets_level = gods[god_address].pet_level; // add pet level to the sum
uint amulet_god_id;
uint amulet_god_level;
for (uint i = 1; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
amulet_god_id = amulets[i].god_id;
amulet_god_level = gods[gods_address[amulet_god_id]].level;
sum_gods_level = add(sum_gods_level, amulet_god_level);
sum_amulets_level = add(sum_amulets_level, amulets[i].level);
}
}
return (sum_gods_level, sum_amulets_level);
}
//admin need this function
function get_listed_winners (uint prize) public view returns (address[]){
address [] memory temp_list = new address[] (count_listed_winners[prize]);
for (uint i = 0; i < count_listed_winners[prize]; i++){
temp_list[i] = listed_winners[prize][add(i,1)];
}
return temp_list;
}
function query_pray () public view returns (uint, uint, uint, address, address, uint, bool){
(uint highest_bid, address highest_bidder) = compare_bid_eth();
return (highest_bid,
pray_egses,
pray_egst,
pray_host_god,
highest_bidder,
count_rounds,
pray_reward_top100);
}
// end of pray
// start of egses
function egses_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
if (reason == 1) {
require (pray_egses > tokens);
pray_egses = sub(pray_egses, tokens);
}
egses_balances[to] = add(egses_balances[to], tokens);
create_change_log(1, reason, tokens, egses_balances[to], contract_address, to);
return true;
}
function egses_withdraw () public returns (uint tokens){
tokens = egses_balances[msg.sender];
require (tokens > 0 && contract_address.balance >= tokens && reEntrancyMutex == false);
reEntrancyMutex = true; // if met problem, it will use up gas from msg.sender and roll back to false
egses_balances[msg.sender] = 0;
msg.sender.transfer(tokens);
reEntrancyMutex = false;
emit withdraw_egses(msg.sender, tokens);
create_change_log(1, 5, tokens, 0, contract_address, msg.sender); // 5 withdraw egses
return tokens;
}
event withdraw_egses (address receiver, uint tokens);
// end of egses
// start of erc20 for egst
function totalSupply () public view returns (uint){
return _totalSupply;
}
function balanceOf (address tokenOwner) public view returns (uint){
return balances[tokenOwner]; // will return 0 if doesn't exist
}
function allowance (address tokenOwner, address spender) public view returns (uint) {
return allowed[tokenOwner][spender];
}
function transfer (address to, uint tokens) public returns (bool success){
require (balances[msg.sender] >= tokens);
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
create_change_log(2, 9, tokens, balances[to], msg.sender, to);
return true;
}
event Transfer (address indexed from, address indexed to, uint tokens);
function approve (address spender, uint tokens) public returns (bool success) {
// if allowed amount used and owner tries to reset allowed amount within a short time,
// the allowed account might be cheating the owner
require (balances[msg.sender] >= tokens);
if (tokens > 0){
require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number);
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
event Approval (address indexed tokenOwner, address indexed spender, uint tokens);
function transferFrom (address from, address to, uint tokens) public returns (bool success) {
require (balances[from] >= tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[from] = sub(balances[from], tokens);
balances[to] = add(balances[to], tokens);
gods[from].allowed_block = block.number;
emit Transfer(from, to, tokens);
create_change_log(2, 10, tokens, balances[to], from, to);
return true;
}
// end of erc20 for egst
// egst
function egst_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
balances[to] = add(balances[to], tokens);
create_change_log(2, reason, tokens, balances[to], contract_address, to);
return true;
}
function egst_to_contract (address from, uint tokens, uint reason) private returns (bool) { // public when testing
require (balances[from] >= tokens);
balances[from] = sub(balances[from], tokens);
emit spend_egst(from, tokens, reason);
create_change_log(2, reason, tokens, balances[from], from, contract_address);
return true;
}
event spend_egst (address from, uint tokens, uint reason);
function create_token_order (uint unit_price, uint egst_amount) public returns (uint) {
require(unit_price >= min_unit_price && unit_price <= max_unit_price
&& balances[msg.sender] >= egst_amount
&& egst_amount <= max_egst_amount
&& egst_amount >= min_egst_amount);
count_token_orders = add(count_token_orders, 1);
egst_to_contract(msg.sender, egst_amount, 3); // 3 create_token_order
token_orders[count_token_orders].start_selling_block = block.number;
token_orders[count_token_orders].seller = msg.sender;
token_orders[count_token_orders].unit_price = unit_price;
token_orders[count_token_orders].egst_amount = egst_amount;
gods[msg.sender].count_token_orders++;
update_first_active_token_order(msg.sender);
return gods[msg.sender].count_token_orders++;
}
function withdraw_token_order (uint order_id) public returns (bool) {
require (msg.sender == token_orders[order_id].seller
&& token_orders[order_id].egst_amount > 0);
uint egst_amount = token_orders[order_id].egst_amount;
token_orders[order_id].start_selling_block = 0;
token_orders[order_id].egst_amount = 0;
// balances[msg.sender] = add(balances[msg.sender], tokens);
egst_from_contract(msg.sender, egst_amount, 4); // 4 withdraw token_order
gods[msg.sender].count_token_orders = sub(gods[msg.sender].count_token_orders, 1);
update_first_active_token_order(msg.sender);
emit WithdrawTokenOrder(msg.sender, order_id);
return true;
}
event WithdrawTokenOrder (address seller, uint order_id);
function buy_token (uint order_id, uint egst_amount) public payable returns (uint) {
require(order_id >= first_active_token_order
&& order_id <= count_token_orders
&& egst_amount <= token_orders[order_id].egst_amount
&& token_orders[order_id].egst_amount > 0);
// unit_price 100 means 1 egst = 0.001 ether
uint eth_cost = div(mul(token_orders[order_id].unit_price, egst_amount), 100000);
require(msg.value >= eth_cost && msg.value < add(eth_cost, max_extra_eth) );
token_orders[order_id].egst_amount = sub(token_orders[order_id].egst_amount, egst_amount);
egst_from_contract(msg.sender, egst_amount, token_orders[order_id].unit_price); // uint price (> 10) will be recorded as reason in change log and translated by front end as buy token & unit_price
// balances[msg.sender] = add(balances[msg.sender], egst_amount);
address seller = token_orders[order_id].seller;
egses_from_contract(seller, eth_cost, 7); // 7 sell egst
if (token_orders[order_id].egst_amount <= 0){
token_orders[order_id].start_selling_block = 0;
gods[seller].count_token_orders = sub(gods[seller].count_token_orders, 1);
update_first_active_token_order(seller);
}
emit BuyToken(msg.sender, order_id, egst_amount);
return token_orders[order_id].egst_amount;
}
event BuyToken (address buyer, uint order_id, uint egst_amount);
function update_first_active_token_order (address god_address) private returns (uint, uint){ // public when testing
if (count_token_orders > 0
&& first_active_token_order == 0){
first_active_token_order = 1;
} else {
for (uint i = first_active_token_order; i <= count_token_orders; i++) {
if (add(token_orders[i].start_selling_block, order_duration) > block.number){
// find the first active order and compare with the currect index
if (i > first_active_token_order){
first_active_token_order = i;
}
break;
}
}
}
if (gods[god_address].count_token_orders > 0
&& gods[god_address].first_active_token_order == 0){
gods[god_address].first_active_token_order = 1; // may not be 1, but it will correct next time
} else {
for (uint j = gods[god_address].first_active_token_order; j < count_token_orders; j++){
if (token_orders[j].seller == god_address
&& token_orders[j].start_selling_block > 0){ // don't check duration, show it to selling, even if expired
// find the first active order and compare with the currect index
if(j > gods[god_address].first_active_token_order){
gods[god_address].first_active_token_order = j;
}
break;
}
}
}
return (first_active_token_order, gods[msg.sender].first_active_token_order);
}
function get_token_order (uint order_id) public view returns(uint, address, uint, uint){
require(order_id >= 1 && order_id <= count_token_orders);
return(token_orders[order_id].start_selling_block,
token_orders[order_id].seller,
token_orders[order_id].unit_price,
token_orders[order_id].egst_amount);
}
// return total orders and lowest price to browser, browser query each active order and show at most three orders of lowest price
function get_token_orders () public view returns(uint, uint, uint, uint, uint) {
uint lowest_price = max_unit_price;
for (uint i = first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].unit_price < lowest_price
&& token_orders[i].egst_amount > 0
&& add(token_orders[i].start_selling_block, order_duration) > block.number){
lowest_price = token_orders[i].unit_price;
}
}
return (count_token_orders, first_active_token_order, order_duration, max_unit_price, lowest_price);
}
function get_my_token_orders () public view returns(uint []) {
uint my_count_token_orders = gods[msg.sender].count_token_orders;
uint [] memory temp_list = new uint[] (my_count_token_orders);
uint count_list_elements = 0;
for (uint i = gods[msg.sender].first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].seller == msg.sender
&& token_orders[i].start_selling_block > 0){
temp_list[count_list_elements] = i;
count_list_elements++;
if (count_list_elements >= my_count_token_orders){
break;
}
}
}
return temp_list;
}
// end of egst
// logs
function get_winner_log (uint pray_round, uint log_id) public view returns (uint, bytes32, address, address, uint, bool){
require(log_id >= 1 && log_id <= count_rounds_winner_logs[pray_round]);
winner_log storage this_winner_log = winner_logs[pray_round][log_id];
return (this_winner_log.god_block_number,
this_winner_log.block_hash,
this_winner_log.prayer,
this_winner_log.previous_winner,
this_winner_log.prize,
this_winner_log.pk_result);
}
function get_count_rounds_winner_logs (uint pray_round) public view returns (uint){
return count_rounds_winner_logs[pray_round];
}
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token (> 10),
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward,
// 9 transfer, 10 transferFrom(owner & receiver)
function create_change_log (uint asset_type, uint reason, uint change_amount, uint after_amount, address _from, address _to) private returns (uint) {
count_rounds_change_logs[count_rounds] = add(count_rounds_change_logs[count_rounds], 1);
uint log_id = count_rounds_change_logs[count_rounds];
change_logs[count_rounds][log_id].block_number = block.number;
change_logs[count_rounds][log_id].asset_type = asset_type;
change_logs[count_rounds][log_id].reason = reason;
change_logs[count_rounds][log_id].change_amount = change_amount;
change_logs[count_rounds][log_id].after_amount = after_amount;
change_logs[count_rounds][log_id]._from = _from;
change_logs[count_rounds][log_id]._to = _to;
return log_id;
}
function get_change_log (uint pray_round, uint log_id) public view returns (uint, uint, uint, uint, uint, address, address){ // public
change_log storage this_log = change_logs[pray_round][log_id];
return (this_log.block_number,
this_log.asset_type,
this_log.reason, // reason > 10 is buy_token unit_price
this_log.change_amount,
this_log.after_amount, // god's after amount. transfer or transferFrom doesn't record log
this_log._from,
this_log._to);
}
function get_count_rounds_change_logs (uint pray_round) public view returns(uint){
return count_rounds_change_logs[pray_round];
}
// end of logs
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsDice {
// ethgods
EthGods private eth_gods;
address private ethgods_contract_address = address(0);// publish ethgods first, then use that address in constructor
function set_eth_gods_contract_address(address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
uint private block_hash_duration;
function update_admin () public returns (bool){
(,,address new_admin, uint new_block_hash_duration,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
block_hash_duration = new_block_hash_duration;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
}
function finalize () public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
function () public payable {
revert(); // if received eth for no reason, reject
}
// end of constructor and destructor
function tell_fortune_blockhash () public view returns (bytes32){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return block_hash;
}
function tell_fortune () public view returns (uint[]){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return throw_dice (block_hash);
}
function throw_dice (bytes32 block_hash) public pure returns (uint[]) {// 0 for prize, 1-6 for 6 numbers should be pure
uint[] memory dice_numbers = new uint[](7);
//uint [7] memory dice_numbers;
uint hash_number;
uint[] memory count_dice_numbers = new uint[](7);
//uint [7] memory count_dice_numbers; // how many times for each dice number
uint i; // for loop
for (i = 1; i <= 6; i++) {
hash_number = uint(block_hash[i]);
// hash_number=1;
if (hash_number >= 214) { // 214
dice_numbers[i] = 6;
} else if (hash_number >= 172) { // 172
dice_numbers[i] = 5;
} else if (hash_number >= 129) { // 129
dice_numbers[i] = 4;
} else if (hash_number >= 86) { // 86
dice_numbers[i] = 3;
} else if (hash_number >= 43) { // 43
dice_numbers[i] = 2;
} else {
dice_numbers[i] = 1;
}
count_dice_numbers[dice_numbers[i]] ++;
}
bool won_super_prize = false;
uint count_super_eth = 0;
for (i = 1; i <= 6; i++) {
if (count_dice_numbers[i] >= 5) {
dice_numbers[0] = 1; //champion_eth
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 4) {
dice_numbers[0] = 3; // super_egst
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 1) {
count_super_eth ++;
if (count_super_eth == 6) {
dice_numbers[0] = 2; // super_eth
won_super_prize = true;
}
}
}
if (won_super_prize == false) {
if (count_dice_numbers[6] >= 2){
dice_numbers[0] = 4; // primary_egst
} else if (count_dice_numbers[6] == 1){
dice_numbers[0] = 5; // lucky_star
}
}
return dice_numbers;
}
function pk (bytes32 block_hash, uint attacker_sum_god_levels, uint attacker_sum_amulet_levels, uint defender_sum_god_levels, uint defender_sum_amulet_levels) public pure returns (bool){
uint god_win_chance;
attacker_sum_god_levels = add(attacker_sum_god_levels, 10);
if (attacker_sum_god_levels < defender_sum_god_levels){
god_win_chance = 0;
} else {
god_win_chance = sub(attacker_sum_god_levels, defender_sum_god_levels);
if (god_win_chance > 20) {
god_win_chance = 100;
} else { // equal level, 50% chance to win
god_win_chance = mul(god_win_chance, 5);
}
}
uint amulet_win_chance;
attacker_sum_amulet_levels = add(attacker_sum_amulet_levels, 10);
if (attacker_sum_amulet_levels < defender_sum_amulet_levels){
amulet_win_chance = 0;
} else {
amulet_win_chance = sub(attacker_sum_amulet_levels, defender_sum_amulet_levels);
if (amulet_win_chance > 20) {
amulet_win_chance = 100;
} else { // equal level, 50% chance to win
amulet_win_chance = mul(amulet_win_chance, 5);
}
}
uint attacker_win_chance = div(add(god_win_chance, amulet_win_chance), 2);
if (attacker_win_chance >= div(mul(uint(block_hash[3]),2),5)){
return true;
} else {
return false;
}
}
// common functions
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub (uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul (uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div (uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
contract EthGodsName {
// EthGods
EthGods private eth_gods;
address private ethgods_contract_address;
function set_eth_gods_contract_address (address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
function update_admin () public returns (bool){
(,,address new_admin,,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private invalid_chars = "\\\"";
bytes private invalid_bytes = bytes(invalid_chars);
function set_invalid_chars (string new_invalid_chars) public returns (bool) {
require(msg.sender == admin);
invalid_chars = new_invalid_chars;
invalid_bytes = bytes(invalid_chars);
return true;
}
uint private valid_length = 16;
function set_valid_length (uint new_valid_length) public returns (bool) {
require(msg.sender == admin);
valid_length = new_valid_length;
return true;
}
struct god_name {
string god_name;
uint block_number;
uint block_duration;
}
mapping (address => god_name) private gods_name;
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
address v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
gods_name[v_god].god_name = "V";
}
function () public payable {
revert(); // if received eth for no reason, reject
}
function finalize() public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
// end of constructor and destructor
function set_god_name (string new_name) public returns (bool){
address god_address = msg.sender;
require (add(gods_name[god_address].block_number, gods_name[god_address].block_duration) < block.number );
bytes memory bs = bytes(new_name);
require (bs.length <= valid_length);
for (uint i = 0; i < bs.length; i++){
for (uint j = 0; j < invalid_bytes.length; j++) {
if (bs[i] == invalid_bytes[j]){
return false;
}
}
}
gods_name[god_address].god_name = new_name;
emit set_name(god_address, new_name);
return true;
}
event set_name (address indexed god_address, string new_name);
function get_god_name (address god_address) public view returns (string) {
return gods_name[god_address].god_name;
}
function block_god_name (address god_address, uint block_duration) public {
require (msg.sender == admin);
gods_name[god_address].god_name = "Unkown";
gods_name[god_address].block_number = block.number;
gods_name[god_address].block_duration = block_duration;
}
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
} | amulet bool selling; uint order_id; should be 0, if not selling | struct amulet {
uint god_id;
address owner;
uint level;
}
uint private count_amulets = 0;
uint private count_waiting_prayers;
mapping(address => uint) egses_balances;
string public symbol = "EGST";
uint private _totalSupply;
mapping(address => mapping(address => uint)) allowed;
| 997,191 | [
1,
301,
332,
278,
1426,
357,
2456,
31,
2254,
1353,
67,
350,
31,
225,
1410,
506,
374,
16,
309,
486,
357,
2456,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
565,
1958,
2125,
332,
278,
288,
203,
3639,
2254,
314,
369,
67,
350,
31,
203,
3639,
1758,
3410,
31,
203,
3639,
2254,
1801,
31,
203,
565,
289,
203,
565,
2254,
3238,
1056,
67,
301,
332,
2413,
273,
374,
31,
7010,
203,
203,
377,
203,
203,
565,
2254,
3238,
1056,
67,
20241,
67,
84,
435,
414,
31,
203,
203,
203,
377,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
425,
564,
281,
67,
70,
26488,
31,
203,
540,
203,
203,
565,
533,
1071,
3273,
273,
315,
41,
43,
882,
14432,
203,
565,
2254,
3238,
389,
4963,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
377,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.4;
import './trace.sol';
contract MerkleVerifier is Trace {
bytes32 constant HASH_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000;
// This function takes a set of data leaves and indices are 2^depth + leaf index and must be sorted in ascending order.
// Note: `leaves` and `indices` will be overwritten in the process
// NOTE - An empty claim will revert
// TODO: Add high level algorithm documentation.
function verify_merkle_proof(
bytes32 root,
bytes32[] memory leaves,
uint256[] memory indices,
bytes32[] memory decommitment
) internal returns (bool valid) {
trace('verify_merkle_proof', true);
require(leaves.length == indices.length, 'Invalid input');
require(leaves.length > 0, 'No claimed data');
// This algorihm does a lot of array indexing and is a major hot path.
// It is implemented in assembly to avoid unecessary bounds checking.
// We rely on 64 bytes of scratch space being available in 0x00..0x40
// (this is where we will store left and right leave for hashing)
// We also rely on arrays having a length prefixed memory layout
// See <https://solidity.readthedocs.io/en/v0.6.6/assembly.html#conventions-in-solidity>
// Finally we make heavy use of the fact that left indices have their lowest
// bit zero, and right indices one.
// For the original non-assembly implementation, see <https://github.com/0xProject/OpenZKP/blob/480b69b9f82ee8319884ce8212682b0be7fa3f39/crypto/stark-verifier-ethereum/contracts/merkle.sol#L11>
assembly {
// Read length and get rid of the length prefices
let length := shl(5, mload(indices))
indices := add(indices, 0x20)
leaves := add(leaves, 0x20)
decommitment := add(decommitment, 0x20)
// Set up ring buffer
// Every next layer will have equal or fewer values, so write_index
// can never overrun read_index.
let read_index := 0
let write_index := 0
for {} 1 {} {
// Read the current index
let index := mload(add(indices, read_index))
// Store leaf hash in scratch space at 0x00 or 0x20 depending on
// the lower bit of index (which indicates left or right node)
mstore(shl(5, and(index, 1)), mload(add(leaves, read_index)))
// Increment read pointer, wrappering around the end
read_index := mod(add(read_index, 0x20), length)
// Stop if we hit the root, which has index 1
if eq(index, 1) {
// Root hash is stored right
valid := eq(mload(0x20), root)
break
}
// Check if the next index in the ring is the right sibbling.
// `index | 1` turns index into the right sibbling (no-op if it already is)
switch eq(or(index, 1), mload(add(indices, read_index)))
case 0 {
// No merge with right sibbling, read a decommitment
// Decommitment goes in left or right, opposite of the index bit.
mstore(shl(5, and(not(index), 1)), mload(decommitment))
// It doesn't matter if we read decommitment beyond the end,
// we would read in garbage and not produce a valid root.
decommitment := add(decommitment, 0x20)
}
default {
// Merg with next item in ring buffer, which is the right sibbling.
// Current must be a left. Right sibbling hash goes into 0x20.
mstore(0x20, mload(add(leaves, read_index)))
read_index := mod(add(read_index, 0x20), length)
}
// New node index is half the current index
mstore(add(indices, write_index), shr(1, index))
// New node left and right leaf are stored in 0x00..0x40
mstore(add(leaves, write_index), and(keccak256(0x00, 0x40), HASH_MASK))
// Increment and wrap the write pointer
write_index := mod(add(write_index, 0x20), length)
}
}
trace('verify_merkle_proof', false);
}
function merkle_leaf_hash(uint256[] memory leaf) internal pure returns (bytes32 hash) {
if (leaf.length == 1) {
hash = (bytes32)(leaf[0]);
} else {
// Equivalent to
// hash = keccak256(abi.encodePacked(leaf)) & HASH_MASK;
// Using assembly for performance
assembly {
// Arrays are stored length-prefixed.
// See <https://solidity.readthedocs.io/en/v0.6.6/assembly.html#conventions-in-solidity>
let len := mload(leaf)
hash := and(keccak256(add(leaf, 0x20), mul(len, 0x20)), HASH_MASK)
}
}
}
}
| Equivalent to hash = keccak256(abi.encodePacked(leaf)) & HASH_MASK; Using assembly for performance Arrays are stored length-prefixed. See <https:solidity.readthedocs.io/en/v0.6.6/assembly.html#conventions-in-solidity> | if (leaf.length == 1) {
hash = (bytes32)(leaf[0]);
assembly {
let len := mload(leaf)
hash := and(keccak256(add(leaf, 0x20), mul(len, 0x20)), HASH_MASK)
}
}
| 5,391,438 | [
1,
22606,
358,
1651,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
12070,
3719,
473,
20857,
67,
11704,
31,
11637,
19931,
364,
9239,
5647,
854,
4041,
769,
17,
3239,
329,
18,
2164,
411,
4528,
30,
30205,
560,
18,
25254,
329,
22280,
18,
1594,
19,
275,
19,
90,
20,
18,
26,
18,
26,
19,
28050,
18,
2620,
591,
24862,
17,
267,
17,
30205,
560,
34,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
309,
261,
12070,
18,
2469,
422,
404,
13,
288,
203,
5411,
1651,
273,
261,
3890,
1578,
21433,
12070,
63,
20,
19226,
203,
5411,
19931,
288,
203,
7734,
2231,
562,
519,
312,
945,
12,
12070,
13,
203,
7734,
1651,
519,
471,
12,
79,
24410,
581,
5034,
12,
1289,
12,
12070,
16,
374,
92,
3462,
3631,
14064,
12,
1897,
16,
374,
92,
3462,
13,
3631,
20857,
67,
11704,
13,
203,
5411,
289,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x7B70695E761EB828aBEd8c4d506f9af3a76eF4b5/sources/ZenChests.sol | * @notice Update the number of free mints claimable per token redeemed from the external ERC721 contract/ | function updateMintsPerClaim(uint256 _mintsPerClaim) external onlyOwner {
mintsPerClaim = _mintsPerClaim;
}
| 3,057,185 | [
1,
1891,
326,
1300,
434,
4843,
312,
28142,
7516,
429,
1534,
1147,
283,
24903,
329,
628,
326,
3903,
4232,
39,
27,
5340,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1089,
49,
28142,
2173,
9762,
12,
11890,
5034,
389,
81,
28142,
2173,
9762,
13,
3903,
1338,
5541,
288,
203,
3639,
312,
28142,
2173,
9762,
273,
389,
81,
28142,
2173,
9762,
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
] |
pragma solidity ^0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 airlineCount;
uint256 flightCount;
mapping(address => uint8) authorizedCaller;
mapping(bytes32 => Flight) private flights;
mapping(address => Airline) private airlines;
// FlightInsurance[] private flightInsurance;
//mapping(address => uint256) private customerCredits;
mapping(bytes32 => uint256) private customerFlightCredits;
mapping(address => uint256) private customerCredits;
mapping(bytes32 => uint256) private flightInsurance;
struct Airline{
bool isRegistered;
bool isFunded;
string airlineCode;
}
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
string flightCode;
}
struct FlightInsurance{
address insuree;
bytes32 flightKey;
uint256 insuranceAmount;
}
/* EVENT DEFINITIONS */
/********************************************************************************************/
event CreditInsured (address insuree, address airline, string flight, uint256 timestamp, uint256 amount);
event AirlineRegistered (address airlineAddress, bool isRegistered, bool isFunded, string airlineCode );
event FlightRegistered (address airline, string flightCode, uint256 timestamp );
event AuthorizedCaller(address caller);
event DeAuthorizedCaller(address caller);
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
address firstAirlineAddress
)
public
{
contractOwner = msg.sender;
airlines[firstAirlineAddress] = Airline({
isRegistered: true,
isFunded: true,
airlineCode: "Sprint"
});
airlineCount = 1;
flightCount= 0;
}
/********************************************************************************************/
/* 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 requireIsCallerAuthorized()
{
require(authorizedCaller[msg.sender] == 1, "Caller is not authorized");
_;
}
modifier verifyOtherAirlinesApproval (uint256 validVotesCount) {
require( airlineCount < 4 || SafeMath.div(SafeMath.mul(validVotesCount, 100), airlineCount) >= 50, "At least 50% airlines should vote to register new airline");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() external view returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/* authorize caller */
function authorizeCaller(address _caller) public returns(bool)
{
authorizedCaller[_caller] = 1;
emit AuthorizedCaller(_caller);
return true;
}
/* deauthorize caller */
function deAuthorizeCaller(address _caller) public returns(bool)
{
delete authorizedCaller[_caller];
//authorizedCaller[_caller] = 0;
emit DeAuthorizedCaller(_caller);
return true;
}
function checkIfCallerAuthorized() external returns(bool)
{
if(authorizedCaller[msg.sender] == 1)
return true ;
else
return false;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline (address airlineAddress, string airlineCode, uint256 validVotesCount) requireIsCallerAuthorized verifyOtherAirlinesApproval(validVotesCount)
external returns (bool)
{
airlines[airlineAddress] = Airline({
isRegistered: true,
isFunded: false,
airlineCode: airlineCode
});
airlineCount = airlineCount +1;
emit AirlineRegistered (airlineAddress,airlines[airlineAddress].isRegistered, airlines[airlineAddress].isFunded, airlines[airlineAddress].airlineCode );
return true;
}
function fundAirline( address _airlineAddress) requireIsCallerAuthorized payable external returns (bool){
if(airlines[_airlineAddress].isRegistered== true){
airlines[_airlineAddress].isFunded = true;
}
return true;
}
function isAirline(address _airlineAddress) requireIsCallerAuthorized external view returns(bool){
bool fundStatus = airlines[_airlineAddress].isFunded ;
return fundStatus;
}
function getAirlineCount() requireIsCallerAuthorized external view returns (uint256){
return airlineCount;
}
function checkAirlinesApproval(uint256 validVotesCount ) requireIsCallerAuthorized external view returns (bool) {
bool flag = airlineCount < 4 || SafeMath.div(SafeMath.mul(validVotesCount, 100), airlineCount) >= 50 ;
return flag;
}
function registerFlight( address airline, string flight, uint256 timestamp, uint8 statusCode) requireIsCallerAuthorized external
{
bytes32 _flightKey = getFlightKey( airline, flight, timestamp );
flights[_flightKey] = Flight({
isRegistered: true,
statusCode: statusCode,
updatedTimestamp: timestamp,
airline: airline,
flightCode: flight
});
flightCount = flightCount +1;
emit FlightRegistered (flights[_flightKey].airline, flights[_flightKey].flightCode, flights[_flightKey].updatedTimestamp );
}
function isFlight(address _airlineAddress, string flight , uint256 timestamp) requireIsCallerAuthorized external view returns(bool){
bytes32 _flightKey = getFlightKey( _airlineAddress, flight, timestamp );
return flights[_flightKey].isRegistered;
}
function processFlightStatus( address airline, string flight, uint256 timestamp, uint8 statusCode ) requireIsCallerAuthorized external
{
bytes32 _flightKey = getFlightKey( airline, flight, timestamp );
flights[_flightKey].statusCode = statusCode;
}
function getPassengerInsuredAmount(address insuree , address airline, string flight, uint256 timestamp) requireIsCallerAuthorized external returns(uint256)
{
bytes32 _passengerflightKey = keccak256(abi.encodePacked(insuree, airline, flight, timestamp));
uint256 amount = flightInsurance[_passengerflightKey] ;
return amount;
}
/*
* @dev Buy insurance for a flight
*
*/
function buy(address insuree , address airline, string flight, uint256 timestamp, uint256 amount) requireIsCallerAuthorized external payable
{
bytes32 _passengerflightKey = keccak256(abi.encodePacked(insuree, airline, flight, timestamp));
flightInsurance[_passengerflightKey] = amount;
}
function getCredits(address insuree) requireIsCallerAuthorized external view returns(uint256){
uint256 credits = customerCredits[insuree];
return credits;
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees ( address insuree, address airline, string flight, uint256 timestamp) requireIsCallerAuthorized external
{
bytes32 _passengerflightKey = keccak256(abi.encodePacked(insuree, airline, flight, timestamp));
uint256 amountToCredit = flightInsurance[_passengerflightKey];
amountToCredit= amountToCredit.mul(15).div(10);
if(flightInsurance[_passengerflightKey] > 0){
customerFlightCredits[_passengerflightKey] = amountToCredit;
customerCredits[insuree]= amountToCredit;
}
emit CreditInsured (insuree, airline, flight, timestamp, amountToCredit);
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay(address insuree , uint256 amount) requireIsCallerAuthorized external payable
{
//only data contract has money
uint256 creditBefore = customerCredits[insuree] ;
require(creditBefore >= amount ,"Caller should have sufficient funds to withdraw");
customerCredits[insuree] = creditBefore.sub(amount);
//insuree.transfer(amount);
}
/**
* @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
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
) requireIsCallerAuthorized
view
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
fund();
}
}
| * @dev Transfers eligible payout funds to insuree/only data contract has moneyinsuree.transfer(amount); | function pay(address insuree , uint256 amount) requireIsCallerAuthorized external payable
{
uint256 creditBefore = customerCredits[insuree] ;
require(creditBefore >= amount ,"Caller should have sufficient funds to withdraw");
customerCredits[insuree] = creditBefore.sub(amount);
}
| 12,648,196 | [
1,
1429,
18881,
21351,
293,
2012,
284,
19156,
358,
316,
2055,
73,
19,
3700,
501,
6835,
711,
15601,
267,
2055,
73,
18,
13866,
12,
8949,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
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,
8843,
12,
2867,
316,
2055,
73,
269,
2254,
5034,
3844,
13,
2583,
2520,
11095,
15341,
3903,
8843,
429,
7010,
565,
288,
203,
4202,
203,
1377,
2254,
5034,
12896,
4649,
273,
225,
6666,
24201,
1282,
63,
267,
2055,
73,
65,
274,
203,
203,
1377,
2583,
12,
20688,
4649,
1545,
3844,
269,
6,
11095,
1410,
1240,
18662,
284,
19156,
358,
598,
9446,
8863,
203,
203,
1377,
6666,
24201,
1282,
63,
267,
2055,
73,
65,
273,
12896,
4649,
18,
1717,
12,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x47830F8f8b54b82b34073B07A56d12Ae272e1A7d/sources/contracts/Crowdfunding.sol | @dev Claim a campaign. Contract Admin or Campaign Creator can apply. @param _campaignId Campaign ID. | function claimCampaign(uint _campaignId) external {
Campaign storage campaign = campaigns[_campaignId];
require(campaign.status == 0, "Campaign is not active");
require(campaign.creator == msg.sender || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not the campaign creator or admin");
require(block.timestamp > campaign.endAt, "Campaign has not ended yet");
require(campaign.amount >= campaign.goal, "Campaign goal has not been reached");
campaigns[_campaignId].status = 1;
delete projectToCampaign[campaign.projectId];
uint amount = campaign.amount;
require(success, "Failed to send Ether");
emit CampaignClaimed(_campaignId);
}
| 5,621,489 | [
1,
9762,
279,
8965,
18,
13456,
7807,
578,
17820,
29525,
848,
2230,
18,
225,
389,
14608,
548,
17820,
1599,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
13432,
12,
11890,
389,
14608,
548,
13,
3903,
288,
203,
3639,
17820,
2502,
8965,
273,
8965,
87,
63,
67,
14608,
548,
15533,
203,
3639,
2583,
12,
14608,
18,
2327,
422,
374,
16,
315,
13432,
353,
486,
2695,
8863,
203,
3639,
2583,
12,
14608,
18,
20394,
422,
1234,
18,
15330,
747,
28335,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
11095,
353,
486,
326,
8965,
11784,
578,
3981,
8863,
203,
3639,
2583,
12,
2629,
18,
5508,
405,
8965,
18,
409,
861,
16,
315,
13432,
711,
486,
16926,
4671,
8863,
203,
3639,
2583,
12,
14608,
18,
8949,
1545,
8965,
18,
27354,
16,
315,
13432,
17683,
711,
486,
2118,
8675,
8863,
203,
203,
3639,
8965,
87,
63,
67,
14608,
548,
8009,
2327,
273,
404,
31,
203,
3639,
1430,
1984,
774,
13432,
63,
14608,
18,
4406,
548,
15533,
203,
203,
3639,
2254,
3844,
273,
8965,
18,
8949,
31,
203,
3639,
2583,
12,
4768,
16,
315,
2925,
358,
1366,
512,
1136,
8863,
203,
203,
3639,
3626,
17820,
9762,
329,
24899,
14608,
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
] |
pragma solidity ^0.8.4;
contract Token{
struct Metadata{
string dateStamp; //author, title, abstractData;
string hash;
address delegatorWallet;
uint256 nodeLocation;
//public can be deleted in order to hide public view of location
//make sure has comes first and then the nodeLocation
string[] tags;
//use tags.push(var) for inserting data;
//tags.length for length
}
mapping (address => Metadata) public docLocation;
//use msg.sender to capture sender's address
function write(string memory _hash,string memory _dateStamp, uint256 _nodeLocation, string[] memory _tags) public{
docLocation[msg.sender]=Metadata(_dateStamp, _hash, msg.sender, _nodeLocation, _tags);
}
function read()public view returns (Metadata memory m){
return(docLocation[msg.sender]);
}
}
| author, title, abstractData;
| string dateStamp; | 7,312,827 | [
1,
4161,
16,
2077,
16,
8770,
751,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
533,
1509,
8860,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xf2F9Dc580289FC127D88f6A6FeF19b0e3c99BBCd/sources/contracts/gsn/BaseRelayRecipient.sol | * return the sender of this call. if the call came through our trusted forwarder, return the original sender. otherwise, return `msg.sender`. should be used in the contract anywhere instead of msg.sender/ @inheritdoc IRelayRecipient At this point we know that the sender is a trusted forwarder, so we trust that the last bytes of msg.data are the verified sender address. extract sender address from the end of msg.data | function _msgSender() internal view virtual override returns (address payable ret) {
if (msg.data.length >= 20 && isTrustedForwarder(msg.sender)) {
assembly {
ret := shr(96, calldataload(sub(calldatasize(), 20)))
}
ret = msg.sender;
}
}
| 9,454,130 | [
1,
2463,
326,
5793,
434,
333,
745,
18,
309,
326,
745,
22497,
3059,
3134,
13179,
364,
20099,
16,
327,
326,
2282,
5793,
18,
3541,
16,
327,
1375,
3576,
18,
15330,
8338,
1410,
506,
1399,
316,
326,
6835,
25651,
3560,
434,
1234,
18,
15330,
19,
632,
10093,
467,
27186,
18241,
2380,
333,
1634,
732,
5055,
716,
326,
5793,
353,
279,
13179,
364,
20099,
16,
1427,
732,
10267,
716,
326,
1142,
1731,
434,
1234,
18,
892,
854,
326,
13808,
5793,
1758,
18,
2608,
5793,
1758,
628,
326,
679,
434,
1234,
18,
892,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3576,
12021,
1435,
2713,
1476,
5024,
3849,
1135,
261,
2867,
8843,
429,
325,
13,
288,
203,
3639,
309,
261,
3576,
18,
892,
18,
2469,
1545,
4200,
597,
353,
16950,
30839,
12,
3576,
18,
15330,
3719,
288,
203,
5411,
19931,
288,
203,
7734,
325,
519,
699,
86,
12,
10525,
16,
745,
72,
3145,
6189,
12,
1717,
12,
1991,
13178,
554,
9334,
4200,
20349,
203,
5411,
289,
203,
5411,
325,
273,
1234,
18,
15330,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "State.sol";
import "LoanMaintenanceEvents.sol";
import "PausableGuardian.sol";
import "InterestHandler.sol";
import "InterestOracle.sol";
import "TickMathV1.sol";
contract LoanMaintenance_2 is State, LoanMaintenanceEvents, PausableGuardian, InterestHandler {
function initialize(
address target)
external
onlyOwner
{
_setTarget(this.transferLoan.selector, target);
_setTarget(this.settleInterest.selector, target);
_setTarget(this.getInterestModelValues.selector, target);
_setTarget(this.getTWAI.selector, target);
}
function getInterestModelValues(
address pool,
bytes32 loanId)
external
view
returns (
uint256 _poolLastUpdateTime,
uint256 _poolPrincipalTotal,
uint256 _poolInterestTotal,
uint256 _poolRatePerTokenStored,
uint256 _poolLastInterestRate,
uint256 _loanPrincipalTotal,
uint256 _loanInterestTotal,
uint256 _loanRatePerTokenPaid)
{
_poolLastUpdateTime = poolLastUpdateTime[pool];
_poolPrincipalTotal = poolPrincipalTotal[pool];
_poolInterestTotal = poolInterestTotal[pool];
_poolRatePerTokenStored = poolRatePerTokenStored[pool];
_poolLastInterestRate = poolLastInterestRate[pool];
_loanPrincipalTotal = loans[loanId].principal;
_loanInterestTotal = loanInterestTotal[loanId];
_loanRatePerTokenPaid = loanRatePerTokenPaid[loanId];
}
function transferLoan(
bytes32 loanId,
address newOwner)
external
nonReentrant
pausable
{
Loan storage loanLocal = loans[loanId];
address currentOwner = loanLocal.borrower;
require(loanLocal.active, "loan is closed");
require(currentOwner != newOwner, "no owner change");
require(
msg.sender == currentOwner ||
delegatedManagers[loanId][msg.sender],
"unauthorized"
);
require(borrowerLoanSets[currentOwner].removeBytes32(loanId), "error in transfer");
borrowerLoanSets[newOwner].addBytes32(loanId);
loanLocal.borrower = newOwner;
emit TransferLoan(
currentOwner,
newOwner,
loanId
);
}
function settleInterest(
bytes32 loanId)
external
pausable
{
// only callable by loan pools
require(loanPoolToUnderlying[msg.sender] != address(0), "not authorized");
_settleInterest(
msg.sender, // loan pool
loanId
);
}
function getTWAI(
address pool)
external
view
returns (uint256)
{
uint32 timeSinceUpdate = uint32(block.timestamp.sub(poolLastUpdateTime[pool]));
return TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean(
uint32(block.timestamp),
[timeSinceUpdate+twaiLength, timeSinceUpdate],
timeSinceUpdate >= 60 ?
TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])) :
poolInterestRateObservations[pool][poolLastIdx[pool]].tick,
poolLastIdx[pool],
uint8(-1)
));
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Constants.sol";
import "Objects.sol";
import "EnumerableBytes32Set.sol";
import "ReentrancyGuard.sol";
import "InterestOracle.sol";
import "Ownable.sol";
import "SafeMath.sol";
contract State is Constants, Objects, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
address public priceFeeds; // handles asset reference price lookups
address public swapsImpl; // handles asset swaps using dex liquidity
mapping (bytes4 => address) public logicTargets; // implementations of protocol functions
mapping (bytes32 => Loan) public loans; // loanId => Loan
mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams
mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order
mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order
mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved
// Interest
mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object (depreciated)
mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object (depreciated)
// Internals
EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set
EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set
address public feesController; // address controlling fee withdrawals
uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments
mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset
mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid)
uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade
mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset
mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid)
uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan
mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset
mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid)
uint256 public protocolTokenHeld; // current protocol token deposit balance
uint256 public protocolTokenPaid; // lifetime total payout of protocol token
uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program
mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken
mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying
mapping (address => address) public underlyingToLoanPool; // underlying => loanPool
EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set
mapping (address => bool) public supportedTokens; // supported tokens for swaps
uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate
uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount
uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH
/**** new interest model start */
mapping(address => uint256) public poolLastUpdateTime; // per itoken
mapping(address => uint256) public poolPrincipalTotal; // per itoken
mapping(address => uint256) public poolInterestTotal; // per itoken
mapping(address => uint256) public poolRatePerTokenStored; // per itoken
mapping(bytes32 => uint256) public loanInterestTotal; // per loan
mapping(bytes32 => uint256) public loanRatePerTokenPaid; // per loan
mapping(address => uint256) internal poolLastInterestRate; // per itoken
mapping(address => InterestOracle.Observation[256]) internal poolInterestRateObservations; // per itoken
mapping(address => uint8) internal poolLastIdx; // per itoken
uint32 public timeDelta;
uint32 public twaiLength;
/**** new interest model end */
function _setTarget(
bytes4 sig,
address target)
internal
{
logicTargets[sig] = target;
if (target != address(0)) {
logicTargetsSet.addBytes32(bytes32(sig));
} else {
logicTargetsSet.removeBytes32(bytes32(sig));
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "IWethERC20.sol";
contract Constants {
uint256 internal constant WEI_PRECISION = 10**18;
uint256 internal constant WEI_PERCENT_PRECISION = 10**20;
uint256 internal constant DAYS_IN_A_YEAR = 365;
uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month
// string internal constant UserRewardsID = "UserRewards"; // decommissioned
string internal constant LoanDepositValueID = "LoanDepositValue";
IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // mainnet
address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; // mainnet
address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; // mainnet
address public constant OOKI = address(0x0De05F6447ab4D22c8827449EE4bA2D5C288379B); // mainnet
//IWethERC20 public constant wethToken = IWethERC20(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // kovan
//address public constant bzrxTokenAddress = 0xB54Fc2F2ea17d798Ad5C7Aba2491055BCeb7C6b2; // kovan
//address public constant vbzrxTokenAddress = 0x6F8304039f34fd6A6acDd511988DCf5f62128a32; // kovan
//IWethERC20 public constant wethToken = IWethERC20(0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6); // local testnet only
//address public constant bzrxTokenAddress = 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87; // local testnet only
//address public constant vbzrxTokenAddress = 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472; // local testnet only
//IWethERC20 public constant wethToken = IWethERC20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); // bsc (Wrapped BNB)
//address public constant bzrxTokenAddress = address(0); // bsc
//address public constant vbzrxTokenAddress = address(0); // bsc
//address public constant OOKI = address(0); // bsc
// IWethERC20 public constant wethToken = IWethERC20(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); // polygon (Wrapped MATIC)
// address public constant bzrxTokenAddress = address(0); // polygon
// address public constant vbzrxTokenAddress = address(0); // polygon
// address public constant OOKI = 0xCd150B1F528F326f5194c012f32Eb30135C7C2c9; // polygon
//IWethERC20 public constant wethToken = IWethERC20(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); // avax (Wrapped AVAX)
//address public constant bzrxTokenAddress = address(0); // avax
//address public constant vbzrxTokenAddress = address(0); // avax
// IWethERC20 public constant wethToken = IWethERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); // arbitrum
// address public constant bzrxTokenAddress = address(0); // arbitrum
// address public constant vbzrxTokenAddress = address(0); // arbitrum
// address public constant OOKI = address(0x400F3ff129Bc9C9d239a567EaF5158f1850c65a4); // arbitrum
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
import "IWeth.sol";
import "IERC20.sol";
contract IWethERC20 is IWeth, IERC20 {}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
interface IWeth {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
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);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "LoanStruct.sol";
import "LoanParamsStruct.sol";
import "OrderStruct.sol";
import "LenderInterestStruct.sol";
import "LoanInterestStruct.sol";
contract Objects is
LoanStruct,
LoanParamsStruct,
OrderStruct,
LenderInterestStruct,
LoanInterestStruct
{}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanStruct {
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanParamsStruct {
struct LoanParams {
bytes32 id; // id of loan params object
bool active; // if false, this object has been disabled by the owner and can't be used for future loans
address owner; // owner of this object
address loanToken; // the token being loaned
address collateralToken; // the required collateral token
uint256 minInitialMargin; // the minimum allowed initial margin
uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value
uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract OrderStruct {
struct Order {
uint256 lockedAmount; // escrowed amount waiting for a counterparty
uint256 interestRate; // interest rate defined by the creator of this order
uint256 minLoanTerm; // minimum loan term allowed
uint256 maxLoanTerm; // maximum loan term allowed
uint256 createdTimestamp; // timestamp when this order was created
uint256 expirationTimestamp; // timestamp when this order expires
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LenderInterestStruct {
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset (DEPRECIATED)
uint256 owedPerDay; // interest owed per day for all loans of asset (DEPRECIATED)
uint256 owedTotal; // total interest owed for all loans of asset (DEPRECIATED)
uint256 paidTotal; // total interest paid so far for asset (DEPRECIATED)
uint256 updatedTimestamp; // last update (DEPRECIATED)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanInterestStruct {
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan (DEPRECIATED)
uint256 depositTotal; // total escrowed interest for loan (DEPRECIATED)
uint256 updatedTimestamp; // last update (DEPRECIATED)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
/**
* @dev Library for managing loan sets
*
* 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.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* 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.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @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 get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @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 getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <[email protected]π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
/// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
uint256 internal constant REENTRANCY_GUARD_FREE = 1;
/// @dev Constant for locked guard state
uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;
/**
* @dev We use a single lock for the whole contract.
*/
uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant");
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
pragma solidity ^0.5.0;
library InterestOracle {
struct Observation {
uint32 blockTimestamp;
int56 irCumulative;
int24 tick;
}
/// @param last The specified observation
/// @param blockTimestamp The new timestamp
/// @param tick The active tick
/// @return Observation The newly populated observation
function convert(
Observation memory last,
uint32 blockTimestamp,
int24 tick
) private pure returns (Observation memory) {
return
Observation({
blockTimestamp: blockTimestamp,
irCumulative: last.irCumulative + int56(tick) * (blockTimestamp - last.blockTimestamp),
tick: tick
});
}
/// @param self oracle array
/// @param index most recent observation index
/// @param blockTimestamp timestamp of observation
/// @param tick active tick
/// @param cardinality populated elements
/// @param minDelta minimum time delta between observations
/// @return indexUpdated The new index
function write(
Observation[256] storage self,
uint8 index,
uint32 blockTimestamp,
int24 tick,
uint8 cardinality,
uint32 minDelta
) internal returns (uint8 indexUpdated) {
Observation memory last = self[index];
// early return if we've already written an observation in last minDelta seconds
if (last.blockTimestamp + minDelta >= blockTimestamp) return index;
indexUpdated = (index + 1) % cardinality;
self[indexUpdated] = convert(last, blockTimestamp, tick);
}
/// @param self oracle array
/// @param target targeted timestamp to retrieve value
/// @param index latest index
/// @param cardinality populated elements
function binarySearch(
Observation[256] storage self,
uint32 target,
uint8 index,
uint8 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
uint256 l = (index + 1) % cardinality; // oldest observation
uint256 r = l + cardinality - 1; // newest observation
uint256 i;
while (true) {
i = (l + r) / 2;
beforeOrAt = self[i % cardinality];
if (beforeOrAt.blockTimestamp == 0) {
l = 0;
r = index;
continue;
}
atOrAfter = self[(i + 1) % cardinality];
bool targetAtOrAfter = beforeOrAt.blockTimestamp <= target;
bool targetBeforeOrAt = atOrAfter.blockTimestamp >= target;
if (!targetAtOrAfter) {
r = i - 1;
continue;
} else if (!targetBeforeOrAt) {
l = i + 1;
continue;
}
break;
}
}
/// @param self oracle array
/// @param target targeted timestamp to retrieve value
/// @param tick current tick
/// @param index latest index
/// @param cardinality populated elements
function getSurroundingObservations(
Observation[256] storage self,
uint32 target,
int24 tick,
uint8 index,
uint8 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
beforeOrAt = self[index];
if (beforeOrAt.blockTimestamp <= target) {
if (beforeOrAt.blockTimestamp == target) {
return (beforeOrAt, atOrAfter);
} else {
return (beforeOrAt, convert(beforeOrAt, target, tick));
}
}
beforeOrAt = self[(index + 1) % cardinality];
if (beforeOrAt.blockTimestamp == 0) beforeOrAt = self[0];
require(beforeOrAt.blockTimestamp <= target && beforeOrAt.blockTimestamp != 0, "OLD");
return binarySearch(self, target, index, cardinality);
}
/// @param self oracle array
/// @param time current timestamp
/// @param secondsAgo lookback time
/// @param index latest index
/// @param cardinality populated elements
/// @return irCumulative cumulative interest rate, calculated with rate * time
function observeSingle(
Observation[256] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint8 index,
uint8 cardinality
) internal view returns (int56 irCumulative) {
if (secondsAgo == 0) {
Observation memory last = self[index];
if (last.blockTimestamp != time) {
last = convert(last, time, tick);
}
return last.irCumulative;
}
uint32 target = time - secondsAgo;
(Observation memory beforeOrAt, Observation memory atOrAfter) =
getSurroundingObservations(self, target, tick, index, cardinality);
if (target == beforeOrAt.blockTimestamp) {
// left boundary
return beforeOrAt.irCumulative;
} else if (target == atOrAfter.blockTimestamp) {
// right boundary
return atOrAfter.irCumulative;
} else {
// middle
return
beforeOrAt.irCumulative +
((atOrAfter.irCumulative - beforeOrAt.irCumulative) / (atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp)) *
(target - beforeOrAt.blockTimestamp);
}
}
/// @param self oracle array
/// @param time current timestamp
/// @param secondsAgos lookback time
/// @param index latest index
/// @param cardinality populated elements
/// @return irCumulative cumulative interest rate, calculated with rate * time
function arithmeticMean(
Observation[256] storage self,
uint32 time,
uint32[2] memory secondsAgos,
int24 tick,
uint8 index,
uint8 cardinality
) internal view returns (int24) {
int56 firstPoint = observeSingle(self, time, secondsAgos[1], tick, index, cardinality);
int56 secondPoint = observeSingle(self, time, secondsAgos[0], tick, index, cardinality);
return int24((firstPoint-secondPoint) / (secondsAgos[0]-secondsAgos[1]));
}
}
pragma solidity ^0.5.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanMaintenanceEvents {
event DepositCollateral(
address indexed user,
address indexed depositToken,
bytes32 indexed loanId,
uint256 depositAmount
);
event WithdrawCollateral(
address indexed user,
address indexed withdrawToken,
bytes32 indexed loanId,
uint256 withdrawAmount
);
// DEPRECATED
event ExtendLoanDuration(
address indexed user,
address indexed depositToken,
bytes32 indexed loanId,
uint256 depositAmount,
uint256 collateralUsedAmount,
uint256 newEndTimestamp
);
// DEPRECATED
event ReduceLoanDuration(
address indexed user,
address indexed withdrawToken,
bytes32 indexed loanId,
uint256 withdrawAmount,
uint256 newEndTimestamp
);
event LoanDeposit(
bytes32 indexed loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
);
// DEPRECATED
event ClaimReward(
address indexed user,
address indexed receiver,
address indexed token,
uint256 amount
);
event TransferLoan(
address indexed currentOwner,
address indexed newOwner,
bytes32 indexed loanId
);
enum LoanType {
All,
Margin,
NonMargin
}
struct LoanReturnData {
bytes32 loanId; // id of the loan
uint96 endTimestamp; // loan end timestamp
address loanToken; // loan token address
address collateralToken; // collateral token address
uint256 principal; // principal amount of the loan
uint256 collateral; // collateral amount of the loan
uint256 interestOwedPerDay; // interest owned per day
uint256 interestDepositRemaining; // remaining unspent interest
uint256 startRate; // collateralToLoanRate
uint256 startMargin; // margin with which loan was open
uint256 maintenanceMargin; // maintenance margin
uint256 currentMargin; /// current margin
uint256 maxLoanTerm; // maximum term of the loan
uint256 maxLiquidatable; // current max liquidatable
uint256 maxSeizable; // current max seizable
uint256 depositValueAsLoanToken; // net value of deposit denominated as loanToken
uint256 depositValueAsCollateralToken; // net value of deposit denominated as collateralToken
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Ownable.sol";
contract PausableGuardian is Ownable {
// keccak256("Pausable_FunctionPause")
bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047;
// keccak256("Pausable_GuardianAddress")
bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf;
modifier pausable {
require(!_isPaused(msg.sig), "paused");
_;
}
modifier onlyGuardian {
require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized");
_;
}
function _isPaused(bytes4 sig) public view returns (bool isPaused) {
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
isPaused := sload(slot)
}
}
function toggleFunctionPause(bytes4 sig) public onlyGuardian {
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 1)
}
}
function toggleFunctionUnPause(bytes4 sig) public onlyGuardian {
// only DAO can unpause, and adding guardian temporarily
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 0)
}
}
function changeGuardian(address newGuardian) public onlyGuardian {
assembly {
sstore(Pausable_GuardianAddress, newGuardian)
}
}
function getGuardian() public view returns (address guardian) {
assembly {
guardian := sload(Pausable_GuardianAddress)
}
}
function pause(bytes4 [] calldata sig)
external
onlyGuardian
{
for(uint256 i = 0; i < sig.length; ++i){
toggleFunctionPause(sig[i]);
}
}
function unpause(bytes4 [] calldata sig)
external
onlyGuardian
{
for(uint256 i = 0; i < sig.length; ++i){
toggleFunctionUnPause(sig[i]);
}
}
}
/**
* Copyright 2017-2021, bZxDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "State.sol";
import "ILoanPool.sol";
import "MathUtil.sol";
import "InterestRateEvents.sol";
import "InterestOracle.sol";
import "TickMathV1.sol";
contract InterestHandler is State, InterestRateEvents {
using MathUtil for uint256;
using InterestOracle for InterestOracle.Observation[256];
// returns up to date loan interest or 0 if not applicable
function _settleInterest(
address pool,
bytes32 loanId)
internal
returns (uint256 _loanInterestTotal)
{
poolLastIdx[pool] = poolInterestRateObservations[pool].write(
poolLastIdx[pool],
uint32(block.timestamp),
TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])),
uint8(-1),
timeDelta
);
uint256[7] memory interestVals = _settleInterest2(
pool,
loanId,
false
);
poolInterestTotal[pool] = interestVals[1];
poolRatePerTokenStored[pool] = interestVals[2];
if (interestVals[3] != 0) {
poolLastInterestRate[pool] = interestVals[3];
emit PoolInterestRateVals(
pool,
interestVals[0],
interestVals[1],
interestVals[2],
interestVals[3]
);
}
if (loanId != 0) {
_loanInterestTotal = interestVals[5];
loanInterestTotal[loanId] = _loanInterestTotal;
loanRatePerTokenPaid[loanId] = interestVals[6];
emit LoanInterestRateVals(
loanId,
interestVals[4],
interestVals[5],
interestVals[6]
);
}
poolLastUpdateTime[pool] = block.timestamp;
}
function _getPoolPrincipal(
address pool)
internal
view
returns (uint256)
{
uint256[7] memory interestVals = _settleInterest2(
pool,
0,
true
);
return interestVals[0] // _poolPrincipalTotal
.add(interestVals[1]); // _poolInterestTotal
}
function _getLoanPrincipal(
address pool,
bytes32 loanId)
internal
view
returns (uint256)
{
uint256[7] memory interestVals = _settleInterest2(
pool,
loanId,
false
);
return interestVals[4] // _loanPrincipalTotal
.add(interestVals[5]); // _loanInterestTotal
}
function _settleInterest2(
address pool,
bytes32 loanId,
bool includeLendingFee)
internal
view
returns (uint256[7] memory interestVals)
{
/*
uint256[7] ->
0: _poolPrincipalTotal,
1: _poolInterestTotal,
2: _poolRatePerTokenStored,
3: _poolNextInterestRate,
4: _loanPrincipalTotal,
5: _loanInterestTotal,
6: _loanRatePerTokenPaid
*/
interestVals[0] = poolPrincipalTotal[pool]
.add(lenderInterest[pool][loanPoolToUnderlying[pool]].principalTotal); // backwards compatibility
interestVals[1] = poolInterestTotal[pool];
uint256 lendingFee = interestVals[1]
.mul(lendingFeePercent)
.divCeil(WEI_PERCENT_PRECISION);
uint256 _poolVariableRatePerTokenNewAmount;
(_poolVariableRatePerTokenNewAmount, interestVals[3]) = _getRatePerTokenNewAmount(pool, interestVals[0].add(interestVals[1] - lendingFee));
interestVals[1] = interestVals[0]
.mul(_poolVariableRatePerTokenNewAmount)
.div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.add(interestVals[1]);
if (includeLendingFee) {
interestVals[1] -= lendingFee;
}
interestVals[2] = poolRatePerTokenStored[pool]
.add(_poolVariableRatePerTokenNewAmount);
if (loanId != 0 && (interestVals[4] = loans[loanId].principal) != 0) {
interestVals[5] = interestVals[4]
.mul(interestVals[2].sub(loanRatePerTokenPaid[loanId])) // _loanRatePerTokenUnpaid
.div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.add(loanInterestTotal[loanId]);
interestVals[6] = interestVals[2];
}
}
function _getRatePerTokenNewAmount(
address pool,
uint256 poolTotal)
internal
view
returns (uint256 ratePerTokenNewAmount, uint256 nextInterestRate)
{
uint256 timeSinceUpdate = block.timestamp.sub(poolLastUpdateTime[pool]);
uint256 benchmarkRate = TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean(
uint32(block.timestamp),
[uint32(timeSinceUpdate+twaiLength), uint32(timeSinceUpdate)],
poolInterestRateObservations[pool][poolLastIdx[pool]].tick,
poolLastIdx[pool],
uint8(-1)
));
if (timeSinceUpdate != 0 &&
(nextInterestRate = ILoanPool(pool)._nextBorrowInterestRate(poolTotal, 0, benchmarkRate)) != 0) {
ratePerTokenNewAmount = timeSinceUpdate
.mul(nextInterestRate) // rate per year
.mul(WEI_PERCENT_PRECISION)
.div(31536000); // seconds in a year
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
interface ILoanPool {
function tokenPrice()
external
view
returns (uint256 price);
function borrowInterestRate()
external
view
returns (uint256);
function _nextBorrowInterestRate(
uint256 totalBorrow,
uint256 newBorrow,
uint256 lastInterestRate)
external
view
returns (uint256 nextRate);
function totalAssetSupply()
external
view
returns (uint256);
function assetBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.8.0;
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract InterestRateEvents {
event PoolInterestRateVals(
address indexed pool,
uint256 poolPrincipalTotal,
uint256 poolInterestTotal,
uint256 poolRatePerTokenStored,
uint256 poolNextInterestRate
);
event LoanInterestRateVals(
bytes32 indexed loanId,
uint256 loanPrincipalTotal,
uint256 loanInterestTotal,
uint256 loanRatePerTokenPaid
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMathV1 {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) public pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), 'T');
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = uint256(-1) / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) public pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R');
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
} | lender => orderParamsId => Order
| mapping (address => mapping (bytes32 => Order)) public lenderOrders; | 213,771 | [
1,
80,
2345,
516,
1353,
1370,
548,
516,
4347,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
261,
2867,
516,
2874,
261,
3890,
1578,
516,
4347,
3719,
1071,
328,
2345,
16528,
31,
5397,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.2;
contract Ownable {
address public owner;
event OWNERSHIPRENOUNCED348(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED910( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
constructor() public {
owner = msg.sender;
}
modifier ONLYOWNER133() { //inject NONSTANDARD NAMING
require(msg.sender == owner);
_;
}
function TRANSFEROWNERSHIP800(address newOwner) public ONLYOWNER133 { //inject NONSTANDARD NAMING
require(newOwner != address(0));
emit OWNERSHIPTRANSFERRED910(owner, newOwner);
owner = newOwner;
}
function RENOUNCEOWNERSHIP965() public ONLYOWNER133 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED348(owner);
owner = address(0);
}
}
library SafeMath {
function MUL451(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function DIV968(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b > 0);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function SUB978(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD466(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
assert(c>=a && c>=b);
return c;
}
}
contract ERC20Basic {
function TOTALSUPPLY948() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF975(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER954(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER596(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20 is ERC20Basic {
function ALLOWANCE236(address owner, address spender) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFERFROM818(address from, address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
function APPROVE732(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event APPROVAL122(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function TOTALSUPPLY948() public view returns (uint256) { //inject NONSTANDARD NAMING
return totalSupply_;
}
function TRANSFER954(address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].SUB978(_value);
balances[_to] = balances[_to].ADD466(_value);
emit TRANSFER596(msg.sender, _to, _value);
return true;
}
function BALANCEOF975(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
function TRANSFERFROM818(address _from, address _to, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].SUB978(_value);
balances[_to] = balances[_to].ADD466(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].SUB978(_value);
emit TRANSFER596(_from, _to, _value);
return true;
}
function APPROVE732(address _spender, uint256 _value) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = _value;
emit APPROVAL122(msg.sender, _spender, _value);
return true;
}
function ALLOWANCE236(address _owner, address _spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return allowed[_owner][_spender];
}
function INCREASEAPPROVAL411(address _spender, uint256 _addedValue) public returns (bool) { //inject NONSTANDARD NAMING
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].ADD466(_addedValue);
emit APPROVAL122(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function DECREASEAPPROVAL474(address _spender, uint256 _subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.SUB978(_subtractedValue);
}
emit APPROVAL122(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract Pausable is Ownable {
event PAUSE560(); //inject NONSTANDARD NAMING
event UNPAUSE665(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED770() { //inject NONSTANDARD NAMING
require(!paused);
_;
}
modifier WHENPAUSED528() { //inject NONSTANDARD NAMING
require(paused);
_;
}
function PAUSE825() ONLYOWNER133 WHENNOTPAUSED770 public { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE560();
}
function UNPAUSE769() ONLYOWNER133 WHENPAUSED528 public { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE665();
}
}
contract PausableToken is StandardToken, Pausable {
function TRANSFER954(address _to, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFER954(_to, _value);
}
function TRANSFERFROM818(address _from, address _to, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING
return super.TRANSFERFROM818(_from, _to, _value);
}
function APPROVE732(address _spender, uint256 _value) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING
return super.APPROVE732(_spender, _value);
}
function INCREASEAPPROVAL411(address _spender, uint256 _addedValue) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING
return super.INCREASEAPPROVAL411(_spender, _addedValue);
}
function DECREASEAPPROVAL474(address _spender, uint256 _subtractedValue) public WHENNOTPAUSED770 returns (bool) { //inject NONSTANDARD NAMING
return super.DECREASEAPPROVAL474(_spender, _subtractedValue);
}
}
contract FFToken is PausableToken {
string public constant name264 = "Fifty Five Token"; //inject NONSTANDARD NAMING
string public constant symbol755 = "FF"; //inject NONSTANDARD NAMING
uint256 public constant decimals786 = 18; //inject NONSTANDARD NAMING
mapping (address => uint256) freezes;
event BURN80(address indexed from, uint256 value); //inject NONSTANDARD NAMING
event FREEZE181(address indexed from, uint256 value); //inject NONSTANDARD NAMING
event UNFREEZE267(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor() public {
totalSupply_ = 10000000000 * (10 ** uint256(decimals786));
balances[msg.sender] = totalSupply_;
}
function FREEZEOF457(address _owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return freezes[_owner];
}
function BURN929(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].SUB978(_value);
totalSupply_ = totalSupply_.SUB978(_value);
emit BURN80(msg.sender, _value);
return true;
}
function FREEZE250(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].SUB978(_value);
freezes[msg.sender] = freezes[msg.sender].ADD466(_value);
emit FREEZE181(msg.sender, _value);
return true;
}
function UNFREEZE512(uint256 _value) WHENNOTPAUSED770 public returns (bool) { //inject NONSTANDARD NAMING
require(_value <= freezes[msg.sender]);
freezes[msg.sender] = freezes[msg.sender].SUB978(_value);
balances[msg.sender] = balances[msg.sender].ADD466(_value);
emit UNFREEZE267(msg.sender, _value);
return true;
}
function TRANSFEROWNERSHIP800(address newOwner) ONLYOWNER133 WHENNOTPAUSED770 public { //inject NONSTANDARD NAMING
super.TRANSFEROWNERSHIP800(newOwner);
}
function() payable external {
revert();
}
} | inject NONSTANDARD NAMING
| event FREEZE181(address indexed from, uint256 value); | 1,045,808 | [
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,
871,
478,
9719,
3794,
2643,
21,
12,
2867,
8808,
628,
16,
2254,
5034,
460,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
import "../interfaces/proxy/IProxyManager.sol";
import "../interfaces/proxy/IProxyActions.sol";
import "../interfaces/proxy/IProxyActionsStorage.sol";
/*
A per-user delegatecall proxy.
When called with data it delegatecalls into ProxyActions.
Authentication checks are performed in ProxyActions.
*/
contract Proxy {
IProxyManager private manager;
IProxyActionsStorage private store;
address private owner;
/*
Constructor is called by ProxyManager.
After the constructor is done, ProxyManager will call setup()
which delegatecalls into the actions contract
*/
constructor(address _owner) public {
manager = IProxyManager(msg.sender);
store = IProxyActionsStorage(manager.proxyActionsStorage());
owner = _owner;
}
/*
When called with data the current addresses for actions and storage
are requested from ProxyManager. Afterwards a delegatecall is performed
into the actions contract. In case the delegatecall fails the contract reverts.
*/
function() external payable {
if(msg.data.length != 0) {
address target = manager.proxyActions();
store = IProxyActionsStorage(manager.proxyActionsStorage());
// solium-disable-next-line security/no-inline-assembly
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas, target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 { revert(0, returndatasize()) }
default { return (0, returndatasize()) }
}
}
}
} | / solium-disable-next-line security/no-inline-assembly | function() external payable {
if(msg.data.length != 0) {
address target = manager.proxyActions();
store = IProxyActionsStorage(manager.proxyActionsStorage());
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas, target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
}
}
}
| 13,127,911 | [
1,
19,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
3903,
8843,
429,
288,
203,
3639,
309,
12,
3576,
18,
892,
18,
2469,
480,
374,
13,
288,
203,
5411,
1758,
1018,
273,
3301,
18,
5656,
6100,
5621,
203,
5411,
1707,
273,
467,
3886,
6100,
3245,
12,
4181,
18,
5656,
6100,
3245,
10663,
203,
203,
5411,
19931,
288,
203,
7734,
745,
892,
3530,
12,
20,
16,
374,
16,
745,
13178,
554,
10756,
203,
7734,
2231,
563,
519,
7152,
1991,
12,
31604,
16,
1018,
16,
374,
16,
745,
13178,
554,
9334,
374,
16,
374,
13,
203,
7734,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
7734,
1620,
563,
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
] |
./partial_match/100/0xc2Ca5f5305169C90843e018BC534F6edf5F2e77f/sources/ChainlinkPriceFeed.sol | * @return the latest updated (not stale) valid (price > 0) price/ | function getPrice(bytes32 _priceFeedKey) external view override returns (uint256) {
AggregatorV3Interface aggregator = priceFeedMap[_priceFeedKey];
requireNonEmptyAddress(address(aggregator));
(, uint256 latestPrice, ) = getLatestRoundData(aggregator);
return formatDecimals(latestPrice, priceFeedDecimalMap[_priceFeedKey]);
}
| 16,646,148 | [
1,
2463,
326,
4891,
3526,
261,
902,
14067,
13,
923,
261,
8694,
405,
374,
13,
6205,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25930,
12,
3890,
1578,
389,
8694,
8141,
653,
13,
3903,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
10594,
639,
58,
23,
1358,
20762,
273,
6205,
8141,
863,
63,
67,
8694,
8141,
653,
15533,
203,
3639,
2583,
23176,
1887,
12,
2867,
12,
10751,
639,
10019,
203,
203,
3639,
261,
16,
2254,
5034,
4891,
5147,
16,
262,
273,
336,
18650,
11066,
751,
12,
10751,
639,
1769,
203,
3639,
327,
740,
31809,
12,
13550,
5147,
16,
6205,
8141,
5749,
863,
63,
67,
8694,
8141,
653,
19226,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.11;
import "@daostack/infra/contracts/votingMachines/IntVoteInterface.sol";
import "@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol";
import "./UniversalScheme.sol";
import "../votingMachines/VotingMachineCallbacks.sol";
/**
* @title UGenericScheme.
* @dev A scheme for proposing and executing calls to an arbitrary function
* on a specific contract on behalf of the organization avatar.
*/
contract UGenericScheme is
UniversalScheme,
VotingMachineCallbacks,
ProposalExecuteInterface
{
event NewCallProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _callData,
uint256 _value,
string _descriptionHash
);
event ProposalExecuted(
address indexed _avatar,
bytes32 indexed _proposalId,
bytes _genericCallReturnValue
);
event ProposalExecutedByVotingMachine(
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event ProposalDeleted(address indexed _avatar, bytes32 indexed _proposalId);
// Details of a voting proposal:
struct CallProposal {
bytes callData;
uint256 value;
bool exist;
bool passed;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address => mapping(bytes32 => CallProposal)) public organizationsProposals;
struct Parameters {
IntVoteInterface intVote;
bytes32 voteParams;
address contractToCall;
}
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
mapping(bytes32 => Parameters) public parameters;
/**
* @dev execution of proposals, can only be called by the voting machine in which the vote is held.
* @param _proposalId the ID of the voting in the voting machine
* @param _decision a parameter of the voting result, 1 yes and 2 is no.
* @return bool success
*/
function executeProposal(bytes32 _proposalId, int256 _decision)
external
onlyVotingMachine(_proposalId)
returns (bool)
{
Avatar avatar = proposalsInfo[msg.sender][_proposalId].avatar;
CallProposal storage proposal = organizationsProposals[address(
avatar
)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed == false, "cannot execute twice");
if (_decision == 1) {
proposal.passed = true;
execute(avatar, _proposalId);
} else {
delete organizationsProposals[address(avatar)][_proposalId];
emit ProposalDeleted(address(avatar), _proposalId);
}
emit ProposalExecutedByVotingMachine(
address(avatar),
_proposalId,
_decision
);
return true;
}
/**
* @dev execution of proposals after it has been decided by the voting machine
* @param _proposalId the ID of the voting in the voting machine
*/
function execute(Avatar _avatar, bytes32 _proposalId) public {
Parameters memory params = parameters[getParametersFromController(
_avatar
)];
CallProposal storage proposal = organizationsProposals[address(
_avatar
)][_proposalId];
require(proposal.exist, "must be a live proposal");
require(proposal.passed, "proposal must passed by voting machine");
proposal.exist = false;
bytes memory genericCallReturnValue;
bool success;
Controller controller = Controller(_avatar.owner());
(success, genericCallReturnValue) = controller.genericCall(
params.contractToCall,
proposal.callData,
_avatar,
proposal.value
);
if (success) {
delete organizationsProposals[address(_avatar)][_proposalId];
emit ProposalDeleted(address(_avatar), _proposalId);
emit ProposalExecuted(
address(_avatar),
_proposalId,
genericCallReturnValue
);
} else {
proposal.exist = true;
}
}
/**
* @dev Hash the parameters, save them if necessary, and return the hash value
* @param _voteParams - voting parameters
* @param _intVote - voting machine contract.
* @return bytes32 -the parameters hash
*/
function setParameters(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public returns (bytes32) {
bytes32 paramsHash = getParametersHash(
_voteParams,
_intVote,
_contractToCall
);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
/**
* @dev propose to call on behalf of the _avatar
* The function trigger NewCallProposal event
* @param _avatar avatar of the organization
* @param _callData - The abi encode data for the call
* @param _value value(ETH) to transfer with the call
* @param _descriptionHash proposal description hash
* @return an id which represents the proposal
*/
function proposeCall(
Avatar _avatar,
bytes memory _callData,
uint256 _value,
string memory _descriptionHash
) public returns (bytes32) {
Parameters memory params = parameters[getParametersFromController(
_avatar
)];
IntVoteInterface intVote = params.intVote;
bytes32 proposalId = intVote.propose(
2,
params.voteParams,
msg.sender,
address(_avatar)
);
organizationsProposals[address(_avatar)][proposalId] = CallProposal({
callData: _callData,
value: _value,
exist: true,
passed: false
});
proposalsInfo[address(params.intVote)][proposalId] = ProposalInfo({
blockNumber: block.number,
avatar: _avatar
});
emit NewCallProposal(
address(_avatar),
proposalId,
_callData,
_value,
_descriptionHash
);
return proposalId;
}
/**
* @dev getContractToCall return the contract this scheme is calling
* @param _avatar address of the organization's avatar
* @return address the address of the contract this scheme is calling to
* on behalf of the avatar
*/
function getContractToCall(Avatar _avatar) public view returns (address) {
return parameters[getParametersFromController(_avatar)].contractToCall;
}
/**
* @dev Hash the parameters, and return the hash value
* @param _voteParams - voting parameters
* @param _intVote - voting machine contract.
* @return bytes32 -the parameters hash
*/
function getParametersHash(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public pure returns (bytes32) {
return
keccak256(abi.encodePacked(_voteParams, _intVote, _contractToCall));
}
}
| * @dev Hash the parameters, save them if necessary, and return the hash value @param _voteParams - voting parameters @param _intVote - voting machine contract. @return bytes32 -the parameters hash/ | function setParameters(
bytes32 _voteParams,
IntVoteInterface _intVote,
address _contractToCall
) public returns (bytes32) {
bytes32 paramsHash = getParametersHash(
_voteParams,
_intVote,
_contractToCall
);
parameters[paramsHash].voteParams = _voteParams;
parameters[paramsHash].intVote = _intVote;
parameters[paramsHash].contractToCall = _contractToCall;
return paramsHash;
}
| 13,076,611 | [
1,
2310,
326,
1472,
16,
1923,
2182,
309,
4573,
16,
471,
327,
326,
1651,
460,
225,
389,
25911,
1370,
300,
225,
331,
17128,
1472,
225,
389,
474,
19338,
225,
300,
331,
17128,
5228,
6835,
18,
327,
1731,
1578,
300,
5787,
1472,
1651,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
22556,
12,
203,
3639,
1731,
1578,
389,
25911,
1370,
16,
203,
3639,
3094,
19338,
1358,
389,
474,
19338,
16,
203,
3639,
1758,
389,
16351,
774,
1477,
203,
565,
262,
1071,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
1731,
1578,
859,
2310,
273,
10028,
2310,
12,
203,
5411,
389,
25911,
1370,
16,
203,
5411,
389,
474,
19338,
16,
203,
5411,
389,
16351,
774,
1477,
203,
3639,
11272,
203,
3639,
1472,
63,
2010,
2310,
8009,
25911,
1370,
273,
389,
25911,
1370,
31,
203,
3639,
1472,
63,
2010,
2310,
8009,
474,
19338,
273,
389,
474,
19338,
31,
203,
3639,
1472,
63,
2010,
2310,
8009,
16351,
774,
1477,
273,
389,
16351,
774,
1477,
31,
203,
3639,
327,
859,
2310,
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
] |
./full_match/1/0x92785FfB89414a2eB0d9fE4f5F4431262fEEAD9a/sources/src/utils/TokenInfo.sol | Action Blocked - Empty document
| require(bytes(_documents[documentName].docURI).length != 0); | 2,939,728 | [
1,
1803,
3914,
329,
300,
8953,
1668,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
3890,
24899,
24795,
63,
5457,
461,
8009,
2434,
3098,
2934,
2469,
480,
374,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x5fA457d49b65313611B1A620A55274D01eC2faB0/sources/TrueFiPool.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin 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 Initializable, 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;
pragma solidity 0.6.10;
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
function _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);
}
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);
}
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);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
) internal virtual {}
}
| 4,026,759 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
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,
4232,
39,
3462,
353,
10188,
6934,
16,
1772,
16,
467,
654,
39,
3462,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2254,
28,
3238,
389,
31734,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2163,
31,
203,
565,
445,
1001,
654,
39,
3462,
67,
11160,
12,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
2713,
12562,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
3639,
389,
31734,
273,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
3849,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
2
] |
./full_match/137/0x8D1b881d899E542368214DDcE1DE2F4D73779A9F/sources/contract-4e54bf79fe.sol | @custom:security-contact [email protected] | contract PayCorpEuro is ERC20 {
pragma solidity ^0.8.2;
constructor() ERC20("PayCorp Euro", "PayCoin Eur") {
_mint(msg.sender, 2000000000000 * 10 ** decimals());
}
}
| 4,690,145 | [
1,
36,
3662,
30,
7462,
17,
8994,
4373,
36,
5419,
6217,
84,
18,
832,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
13838,
6217,
84,
41,
19321,
353,
4232,
39,
3462,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
22,
31,
203,
565,
3885,
1435,
4232,
39,
3462,
2932,
9148,
6217,
84,
512,
19321,
3113,
315,
9148,
27055,
512,
295,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
576,
12648,
2787,
380,
1728,
2826,
15105,
10663,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-19
*/
// File: @openzeppelin/contracts/utils/structs/EnumerableSet.sol
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/IAccessControl.sol
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
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;
}
// File: @openzeppelin/contracts/access/AccessControl.sol
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: @openzeppelin/contracts/access/IAccessControlEnumerable.sol
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File: @openzeppelin/contracts/access/AccessControlEnumerable.sol
// OpenZeppelin Contracts v4.4.1 (access/AccessControlEnumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {_grantRole} to track enumerable memberships
*/
function _grantRole(bytes32 role, address account) internal virtual override {
super._grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {_revokeRole} to track enumerable memberships
*/
function _revokeRole(bytes32 role, address account) internal virtual override {
super._revokeRole(role, account);
_roleMembers[role].remove(account);
}
}
// File: ESombra_erc20_final.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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);
}
/**
* @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);
}
}
interface SwapAndLiquifier {
function swapAndLiquify(uint256 contractTokenBalance) external;
}
contract Sombra is Context, IERC20Metadata, Ownable, AccessControlEnumerable {
string private constant NAME = "SOMBRA";
string private constant SYMBOL = "SMBR";
uint8 private constant DECIMALS = 9;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
mapping (address => bool) private _isExcluded;
uint256 private constant MAX_INT = ~uint256(0);
uint256 private TOTAL_SUPPLY = 0;
uint256 private MAX_SUPPLY = 100000000 * 10**DECIMALS;
uint256 private REFLECTION_TOTAL = (MAX_INT - (MAX_INT % MAX_SUPPLY));
uint256 private _tFeeTotal;
// _tSupply and _rSupply keep track of the reflection-tokens supply.
// Essentially, they are the total supply minus balances of excluded addresses.
uint256 private _tSupply = 0;
uint256 private _rSupply = 0;
uint256 public _taxFee = 3;
uint256 public _liquidityFee = 3;
event TaxFeeUpdated(uint256 oldTaxFee, uint256 newTaxFee);
event LiquidityFeeUpdated(uint256 oldLiqFee, uint256 newLiqFee);
// IUniswapV2Router02 public uniswapV2Router;
// IUniswapV2Pair public uniswapV2Pair;
// address private WETH;
event UniswapRouterUpdated(address newRouter);
mapping (address => bool) public marketPair;
event MarketPairUpdated(address pair, bool isMarketPair);
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 private numTokensSellToAddToLiquidity = 100000 * 10**DECIMALS;
// current swapAndLiquify contract address
address swap_and_liquify_contract;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event ExcludedFromReward(address account);
event IncludedInReward(address account);
event ExcludedFromFee(address account);
event IncludedInFee(address account);
// burn permissions
bool burn_approval_required = false;
mapping (address => bool) public give_right_to_burn;
// events and variables for crosschain
event LogSwapin(bytes32 indexed txhash, address indexed account, uint amount);
event LogSwapout(address indexed account, address indexed bindaddr, uint amount);
// flag to enable/disable swapout vs vault.burn so multiple events are triggered
// Disable/Enable swapout for v1 tokens vs mint/burn for v3 tokens
bool private _vaultOnly = false;
address public vault;
function setVaultOnly(bool enabled) external onlyOperator() {
_vaultOnly = enabled;
}
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
// roles for access control //
bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
bytes32 public constant VAULT_ROLE = keccak256("VAULT_ROLE");
constructor() {
// set up roles
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(OPERATOR_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(BURNER_ROLE, _msgSender());
_setupRole(VAULT_ROLE, _msgSender());
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
uint256 chainId;
assembly {chainId := chainid()}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("SOMBRA")),
keccak256(bytes("1")),
chainId,
address(this)));
}
modifier onlyOperator() {
require(
hasRole(OPERATOR_ROLE, _msgSender()),
'must have operator role to use this function'
);
_;
}
function name() public pure override returns (string memory) {
return NAME;
}
function symbol() public pure override returns (string memory) {
return SYMBOL;
}
function decimals() public pure override returns (uint8) {
return DECIMALS;
}
function totalSupply() public view override returns (uint256) {
return TOTAL_SUPPLY;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function isExcludedFromReward(address account) external view returns (bool) {
return _isExcluded[account];
}
function taxCollected() external view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) external {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,,) = _getValues(tAmount, false);
_rOwned[sender] = _rOwned[sender] - rAmount;
_rSupply = _rSupply - rAmount;
_tFeeTotal = _tFeeTotal + tAmount;
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= MAX_SUPPLY, "Amount must be less than supply");
(,uint256 rTransferAmount,,,,,) = _getValues(tAmount, deductTransferFee);
return rTransferAmount;
}
function tokenFromReflection(uint256 rAmount) private view returns(uint256) {
require(rAmount <= _rSupply, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount / currentRate;
}
function excludeFromReward(address account) external onlyOperator() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
uint256 rBalance = _rOwned[account];
if(rBalance > 0) {
uint256 rTokens = tokenFromReflection(rBalance);
_tOwned[account] = rTokens;
_rSupply -= rBalance;
_tSupply -= rTokens;
}
_isExcluded[account] = true;
emit ExcludedFromReward(account);
}
function includeInReward(address account) external onlyOperator() {
require(_isExcluded[account], "Account is already excluded");
uint256 tOwned = _tOwned[account];
uint256 rAmount = reflectionFromToken(tOwned, false);
_tSupply += tOwned;
_rSupply += rAmount;
_rOwned[account] = rAmount;
_tOwned[account] = 0;
_isExcluded[account] = false;
emit IncludedInReward(account);
}
function burn(address from, uint256 amount) public returns(bool){
// require this is called to burn your own tokens or an address that has the BURNER_ROLE
require(from == _msgSender() ||
hasRole(BURNER_ROLE, _msgSender()) ||
hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO BURN");
if (from != _msgSender()){
uint256 currentAllowance = _allowances[from][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(from, _msgSender(), currentAllowance - amount);
}
}
require(from != address(0), "do not burn from the zero address");
// determine if the address from which tokens are being burned is excluded from reflective rewards
bool isExcludedSender = _isExcluded[from];
if (isExcludedSender){
//check that in fact the _tOwned of the burner is greater than the ammount requested to be burned
require(_tOwned[from] >= amount, "in burn: not enough balance owned by from address");
_tOwned[from] -= amount;
// emit the transfer event to indicate the burning to the "zero" address
emit Transfer(from,address(0), amount);
TOTAL_SUPPLY -= amount;
// return true successful burning
return true;
}
// if control gets to here then the burner address is included in the reward
// we will calculate the appropriate ammount of reflection to remove
uint256 rAmount = reflectionFromToken(amount, false);
//check that in fact the _rOwned of the burner is greater than the calculated ammount
require(_rOwned[from] >= rAmount, "in burn: not enough balance owned by from address");
unchecked {
_rOwned[from] -= rAmount;
}
_rSupply -= rAmount;
_tSupply -= amount;
emit Transfer(from, address(0), amount);
TOTAL_SUPPLY -= amount;
// return true successful burning
return true;
}
function mint(address to, uint256 amount) public returns(bool) {
// require this is called by an address that has the MINTER_ROLE
require(hasRole(MINTER_ROLE, _msgSender()) ||
hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO MINT");
require((TOTAL_SUPPLY + amount) <= MAX_SUPPLY, "Minting over MAX_SUPPLY is not permitted");
require(to != address(0), "do not mint to the zero address");
// determine if recipient is excluded from reflective rewards
bool isExcludedRecipient = _isExcluded[to];
// if the reciever is excluded from the reward then simply increase the _tOwned amount by
// the desired amount of tokens
if (isExcludedRecipient){
_tOwned[to] += amount;
// emit the transfer event to indicate the minting from the "zero" address
emit Transfer(address(0), to, amount);
// now increase the total supply of the token by the ammount
TOTAL_SUPPLY += amount;
// return true successful minting
return true;
}
// if control gets to here then the recipient of the mint is included in the reward
// we will calculate the appropriate ammount of reflection to give them
uint256 rAmount = reflectionFromToken(amount, false);
// now based on the amount of tokens minted and the reflection amount change the _tSupply
// and the _rSupply respectively
_tSupply += amount;
_rSupply += rAmount;
// increast the _rOwned of the recipient
_rOwned[to] += rAmount;
// emit the transfer event to indicate the minting from the "zero" address
emit Transfer(address(0), to, amount);
// now increase the total supply of the token by the ammount
TOTAL_SUPPLY += amount;
// return true successful minting
return true;
}
/// the following Swapin and Swapout functions are for the benifit of anyswap bridge capabilities
//
function Swapin(bytes32 txhash, address account, uint256 amount) public returns (bool) {
// require this is called by an address that has the MINTER_ROLE
require(hasRole(MINTER_ROLE, _msgSender()) ||
hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO MINT");
mint(account, amount);
emit LogSwapin(txhash, account, amount);
return true;
}
function Swapout(uint256 amount, address bindaddr) public returns (bool) {
require(!_vaultOnly, "AnyswapV4ERC20: onlyAuth");
require(bindaddr != address(0), "AnyswapV3ERC20: address(0x0)");
burn(_msgSender(), amount);
emit LogSwapout(_msgSender(), bindaddr, amount);
return true;
}
function changeVault(address newVault) external returns (bool) {
// require vault has access now //
require(hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO CHANGE VAULT");
vault = newVault;
// give vault minting burning swapin and swapout rights //
return true;
}
// for compatibility for older versions
function changeMPCOwner(address newVault) external returns (bool) {
// require vault has access now //
require(hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO CHANGE VAULT");
vault = newVault;
// give vault minting burning swapin and swapout rights //
return true;
}
/////////
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant TRANSFER_TYPEHASH = keccak256("Transfer(address owner,address to,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public immutable DOMAIN_SEPARATOR;
/// @dev Records current ERC2612 nonce for account. This value must be included whenever signature is generated for {permit}.
/// Every successful call to {permit} increases account's nonce by one. This prevents signature from being used multiple times.
mapping (address => uint256) public nonces;
/// @dev Sets `value` as allowance of `spender` account over `owner` account's AnyswapV3ERC20 token, given `owner` account's signed approval.
/// Emits {Approval} event.
/// Requirements:
/// - `deadline` must be timestamp in future.
/// - `v`, `r` and `s` must be valid `secp256k1` signature from `owner` account over EIP712-formatted function arguments.
/// - the signature must use `owner` account's current nonce (see {nonces}).
/// - the signer cannot be zero address and must be `owner` account.
/// For more information on signature format, see https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP section].
/// AnyswapV3ERC20 token implementation adapted from https://github.com/albertocuestacanada/ERC20Permit/blob/master/contracts/ERC20Permit.sol.
function permit(address target, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external {
require(block.timestamp <= deadline, "AnyswapV3ERC20: Expired permit");
bytes32 hashStruct = keccak256(
abi.encode(
PERMIT_TYPEHASH,
target,
spender,
value,
nonces[target]++,
deadline));
require(verifyEIP712(target, hashStruct, v, r, s) || verifyPersonalSign(target, hashStruct, v, r, s));
_approve(target, spender, value);
emit Approval(target, spender, value);
}
function verifyEIP712(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
hashStruct));
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
function verifyPersonalSign(address target, bytes32 hashStruct, uint8 v, bytes32 r, bytes32 s) internal view returns (bool) {
bytes32 hash = prefixed(hashStruct);
address signer = ecrecover(hash, v, r, s);
return (signer != address(0) && signer == target);
}
// Builds a prefixed hash to mimic the behavior of eth_sign.
function prefixed(bytes32 hash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", DOMAIN_SEPARATOR, hash));
}
/////
///
function excludeFromFee(address account) external onlyOperator {
_isExcludedFromFee[account] = true;
emit ExcludedFromFee(account);
}
function includeInFee(address account) external onlyOperator {
_isExcludedFromFee[account] = false;
emit IncludedInFee(account);
}
function setTaxFee(uint256 taxFee) external onlyOperator {
require(taxFee + _liquidityFee <= 6, "Fees cannot exceed 6%");
uint256 currentTaxFee = _taxFee;
require(taxFee != currentTaxFee, "Tax fee cannot be the same");
_taxFee = taxFee;
emit TaxFeeUpdated(currentTaxFee, taxFee);
}
function setLiquidityFee(uint256 liquidityFee) external onlyOperator {
require(_taxFee + liquidityFee <= 6, "Fees cannot exceed 6%");
uint256 currentLiqFee = _liquidityFee;
require(liquidityFee != currentLiqFee, "Liquidity fee cannot be the same");
_liquidityFee = liquidityFee;
emit LiquidityFeeUpdated(currentLiqFee, liquidityFee);
}
function setMinTokensToSwapAndLiquify(uint256 minTokens) external onlyOperator {
numTokensSellToAddToLiquidity = minTokens * 10**DECIMALS;
emit MinTokensBeforeSwapUpdated(numTokensSellToAddToLiquidity);
}
function setSwapAndLiquifyEnabled(bool _enabled) external onlyOperator {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
// function to change the swapAndLiquify contract //
function setSwapAndLiquifyContractAddress(address newAddress) public onlyOperator {
address oldAddress = swap_and_liquify_contract;
swap_and_liquify_contract = newAddress;
// Approve the new router to spend contract's tokens.
_approve(address(this), newAddress, MAX_INT);
// Reset approval on old router. and prevent failure if address is not set/ set to address(0)
if (oldAddress != address(0)){
_approve(address(this), oldAddress, 0);
}
}
function updateMarketPair(address pair, bool isPair) external onlyOperator {
_updateMarketPair(pair, isPair);
}
function _updateMarketPair(address pair, bool isPair) private {
require(marketPair[pair] != isPair, "Pair already set");
marketPair[pair] = isPair;
emit MarketPairUpdated(pair, isPair);
}
// burn permissions setters
function setBurningApprovalRequired(bool allow) external onlyOperator(){
burn_approval_required = allow;
}
function setAllowBurning(bool allow) external {
give_right_to_burn[_msgSender()] = allow;
}
// this is to recover erc20 tokens in this contract
// or to manually add liquidity if not using swapandliquify
function transferToken(address token, uint amount, address receiver) onlyOperator() public{
IERC20 erc20 = IERC20(token);
erc20.transfer(receiver, amount);
}
// Use struct for RValues to prevent stack too deep error.
struct _RValues {
uint256 rAmount;
uint256 rTransferAmount;
uint256 rFee;
uint256 rLiquidity;
}
// Retrieves rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity for provided tAmount.
function _getValues(uint256 tAmount, bool takeFee) private view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256) {
if(!takeFee) {
uint256 rTokens = tAmount * _getRate();
return (rTokens, rTokens, 0, tAmount, 0, 0, 0);
}
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
_RValues memory r = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (r.rAmount, r.rTransferAmount, r.rFee, tTransferAmount, tFee, tLiquidity, r.rLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount - tFee - tLiquidity;
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (_RValues memory) {
uint256 rAmount = tAmount * currentRate;
uint256 rFee = tFee * currentRate;
uint256 rLiquidity = tLiquidity * currentRate;
uint256 rTransferAmount = rAmount - rFee - rLiquidity;
return _RValues(
rAmount,
rTransferAmount,
rFee,
rLiquidity
);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply / tSupply;
}
function _getCurrentSupply() private view returns(uint256, uint256) {
// _tSupply is 0 when every token is held by excluded wallet.
uint256 tSupply = _tSupply;
if(tSupply == 0) return (REFLECTION_TOTAL, MAX_SUPPLY);
return (_rSupply, tSupply);
}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rSupply = _rSupply - rFee;
_tFeeTotal = _tFeeTotal + tFee;
}
function _takeLiquidity(address sender, uint256 rLiquidity, uint256 tLiquidity) private {
if(_isExcluded[address(this)]) {
_tOwned[address(this)] = _tOwned[address(this)] + tLiquidity;
_rSupply -= rLiquidity;
_tSupply -= tLiquidity;
} else {
_rOwned[address(this)] = _rOwned[address(this)] + rLiquidity;
}
emit Transfer(sender, address(this), tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount * _taxFee / (10 ** 2);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount * _liquidityFee / (10 ** 2);
}
function isExcludedFromFee(address account) external view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
bool isRecipientMarketPair = marketPair[to];
bool isSenderMarketPair = marketPair[from];
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
uint256 numTokens = numTokensSellToAddToLiquidity;
bool overMinTokenBalance = contractTokenBalance >= numTokens;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
isRecipientMarketPair && // Only swap & liquify on sells.
!isSenderMarketPair &&
swapAndLiquifyEnabled
) {
// Try to swap and liquify.
inSwapAndLiquify = true;
// swapper is approved and does a transferfrom then executes the appropriate liquidity logic
// factored out so that different liquidity interfaces can be supported
SwapAndLiquifier swapper = SwapAndLiquifier(swap_and_liquify_contract);
try swapper.swapAndLiquify(contractTokenBalance) {} catch {
}
inSwapAndLiquify = false;
}
// Only deduct fee if the transaction is to/from the market pair.
bool takeFee = (isRecipientMarketPair || isSenderMarketPair);
//if any account belongs to _isExcludedFromFee account then remove the fee
if(takeFee && (_isExcludedFromFee[from] || _isExcludedFromFee[to])) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee) private {
bool isExcludedSender = _isExcluded[sender];
bool isExcludedRecipient = _isExcluded[recipient];
if (isExcludedSender && !isExcludedRecipient) {
_transferFromExcluded(sender, recipient, amount, takeFee);
} else if (!isExcludedSender && isExcludedRecipient) {
_transferToExcluded(sender, recipient, amount, takeFee);
} else if (!isExcludedSender && !isExcludedRecipient) {
_transferStandard(sender, recipient, amount, takeFee);
} else if (isExcludedSender && isExcludedRecipient) {
_transferBothExcluded(sender, recipient, amount, takeFee);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount, bool takeFee) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee);
require(_rOwned[sender] >= rAmount, "Insufficient Balance");
unchecked {
_rOwned[sender] -= rAmount;
}
_rOwned[recipient] += rTransferAmount;
// Do not have to change the supply when transfering from/to standard accounts.
if(tLiquidity != 0) {
_takeLiquidity(sender, rLiquidity, tLiquidity);
}
if(tFee != 0) {
_reflectFee(rFee, tFee);
}
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee);
require(_tOwned[sender] >= tAmount, "Insufficient Balance");
unchecked {
_tOwned[sender] -= tAmount;
}
_tOwned[recipient] += tTransferAmount;
// Increase the supply by amount spent on taxes. As that amount is no longer held by an excluded wallet.
_rSupply += (rAmount - rTransferAmount);
_tSupply += (tAmount - tTransferAmount);
if(tLiquidity != 0) {
_takeLiquidity(sender, rLiquidity, tLiquidity);
}
if(tFee != 0) {
_reflectFee(rFee, tFee);
}
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee);
require(_rOwned[sender] >= rAmount, "Insufficient Balance");
unchecked {
_rOwned[sender] -= rAmount;
}
_tOwned[recipient] += tTransferAmount;
// Decrease the supply by the amount of tokens the user received, as that is now held by an excluded wallet.
_rSupply -= rTransferAmount;
_tSupply -= tTransferAmount;
if(tLiquidity != 0) {
_takeLiquidity(sender, rLiquidity, tLiquidity);
}
if(tFee != 0) {
_reflectFee(rFee, tFee);
}
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount, bool takeFee) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity, uint256 rLiquidity) = _getValues(tAmount, takeFee);
require(_tOwned[sender] >= tAmount, "Insufficient Balance");
unchecked {
_tOwned[sender] -= tAmount;
}
_rOwned[recipient] += rTransferAmount;
// Increase the supply by the amount of tokens the user sent, as that is no longer held by an excluded wallet.
_rSupply += rAmount;
_tSupply += tAmount;
if(tLiquidity != 0) {
_takeLiquidity(sender, rLiquidity, tLiquidity);
}
if(tFee != 0) {
_reflectFee(rFee, tFee);
}
emit Transfer(sender, recipient, tTransferAmount);
}
} | require this is called to burn your own tokens or an address that has the BURNER_ROLEcheck that in fact the _tOwned of the burner is greater than the ammount requested to be burned emit the transfer event to indicate the burning to the "zero" address return true successful burning | function burn(address from, uint256 amount) public returns(bool){
require(from == _msgSender() ||
hasRole(BURNER_ROLE, _msgSender()) ||
hasRole(OPERATOR_ROLE, _msgSender()) ||
_msgSender() == vault
,"DOES NOT HAVE RIGHT TO BURN");
if (from != _msgSender()){
uint256 currentAllowance = _allowances[from][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(from, _msgSender(), currentAllowance - amount);
}
}
require(from != address(0), "do not burn from the zero address");
if (isExcludedSender){
require(_tOwned[from] >= amount, "in burn: not enough balance owned by from address");
_tOwned[from] -= amount;
emit Transfer(from,address(0), amount);
TOTAL_SUPPLY -= amount;
return true;
}
unchecked {
_rOwned[from] -= rAmount;
}
_rSupply -= rAmount;
_tSupply -= amount;
emit Transfer(from, address(0), amount);
TOTAL_SUPPLY -= amount;
}
| 8,019,202 | [
1,
6528,
333,
353,
2566,
358,
18305,
3433,
4953,
2430,
578,
392,
1758,
716,
711,
326,
605,
8521,
654,
67,
16256,
1893,
716,
316,
5410,
326,
389,
88,
5460,
329,
434,
326,
18305,
264,
353,
6802,
2353,
326,
2125,
4778,
3764,
358,
506,
18305,
329,
3626,
326,
7412,
871,
358,
10768,
326,
18305,
310,
358,
326,
315,
7124,
6,
1758,
327,
638,
6873,
18305,
310,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
377,
445,
18305,
12,
2867,
628,
16,
2254,
5034,
3844,
13,
1071,
1135,
12,
6430,
15329,
203,
3639,
2583,
12,
2080,
422,
389,
3576,
12021,
1435,
747,
7010,
3639,
28335,
12,
38,
8521,
654,
67,
16256,
16,
389,
3576,
12021,
10756,
747,
203,
3639,
28335,
12,
26110,
67,
16256,
16,
389,
3576,
12021,
10756,
747,
7010,
3639,
389,
3576,
12021,
1435,
422,
9229,
203,
3639,
269,
6,
3191,
3991,
4269,
21926,
3412,
13135,
8493,
605,
8521,
8863,
203,
203,
3639,
309,
261,
2080,
480,
389,
3576,
12021,
10756,
95,
203,
5411,
2254,
5034,
783,
7009,
1359,
273,
389,
5965,
6872,
63,
2080,
6362,
67,
3576,
12021,
1435,
15533,
203,
5411,
2583,
12,
2972,
7009,
1359,
1545,
3844,
16,
315,
654,
39,
3462,
30,
7412,
3844,
14399,
1699,
1359,
8863,
203,
5411,
22893,
288,
203,
7734,
389,
12908,
537,
12,
2080,
16,
389,
3576,
12021,
9334,
783,
7009,
1359,
300,
3844,
1769,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
2896,
486,
18305,
628,
326,
3634,
1758,
8863,
203,
203,
3639,
309,
261,
291,
16461,
12021,
15329,
203,
5411,
2583,
24899,
88,
5460,
329,
63,
2080,
65,
1545,
3844,
16,
315,
267,
18305,
30,
486,
7304,
11013,
16199,
635,
628,
1758,
8863,
203,
203,
5411,
389,
88,
5460,
329,
63,
2080,
65,
3947,
3844,
31,
203,
203,
5411,
3626,
12279,
12,
2080,
16,
2867,
12,
20,
3631,
3844,
1769,
203,
203,
5411,
399,
19851,
67,
13272,
23893,
3947,
3844,
31,
203,
5411,
327,
638,
31,
2
] |
./full_match/80001/0x1DD06Da669E411c8147AfcBAFa6B9a1146B11539/sources/project_/contracts/interface/ISTokensManager.sol | @dev The event fired when toke uri freezed. @param tokenId The ID of the freezed token uri @param freezingUser user of freezed token uri/ | event Freezed(uint256 tokenId, address freezingUser);
| 5,567,908 | [
1,
1986,
871,
15950,
1347,
946,
73,
2003,
4843,
94,
329,
18,
225,
1147,
548,
1021,
1599,
434,
326,
4843,
94,
329,
1147,
2003,
225,
4843,
94,
310,
1299,
729,
434,
4843,
94,
329,
1147,
2003,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
2575,
15217,
94,
329,
12,
11890,
5034,
1147,
548,
16,
1758,
4843,
94,
310,
1299,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x3642189B7754302DF84B6F3FE1aE34D2026647A7/sources/src/ConveyorRouterV1.sol | @notice Swap tokens for tokens. @param swapData The swap data for the transaction. @param genericMulticall Multicall to be executed.@notice Transfer tokenIn from msg.sender to tokenInDestination address.@notice Get tokenOut balance of msg.sender.@notice Calculate tokenOut amount required.@notice Execute Multicall.@notice Check if tokenOut balance of msg.sender is sufficient.@dev First bit of referrer is used to check if referrer exists | function swapExactTokenForToken(
TokenToTokenSwapData calldata swapData,
SwapAggregatorMulticall calldata genericMulticall
) public payable {
IERC20(swapData.tokenIn).transferFrom(msg.sender, genericMulticall.tokenInDestination, swapData.amountIn);
uint256 balanceBefore = IERC20(swapData.tokenOut).balanceOf(msg.sender);
uint256 tokenOutAmountRequired = balanceBefore + swapData.amountOutMin;
IConveyorMulticall(CONVEYOR_MULTICALL).executeMulticall(genericMulticall);
uint256 balanceAfter = IERC20(swapData.tokenOut).balanceOf(msg.sender);
if (balanceAfter < tokenOutAmountRequired) {
revert InsufficientOutputAmount(tokenOutAmountRequired - balanceAfter, swapData.amountOutMin);
}
if (swapData.affiliate & 0xFFFF != 0x0) {
address affiliate = affiliates[swapData.affiliate >> 0x1];
if (affiliate == address(0)) {
revert AffiliateDoesNotExist();
}
_safeTransferETH(affiliate, ConveyorMath.mul64U(AFFILIATE_PERCENT, msg.value));
}
if (swapData.referrer & 0xFFFF != 0x0) {
address referrer = referrers[swapData.referrer >> 0x1];
if (referrer == address(0)) {
revert ReferrerDoesNotExist();
}
_safeTransferETH(referrer, ConveyorMath.mul64U(REFERRAL_PERCENT, msg.value));
}
}
| 3,016,251 | [
1,
12521,
2430,
364,
2430,
18,
225,
7720,
751,
1021,
7720,
501,
364,
326,
2492,
18,
225,
5210,
5049,
335,
454,
7778,
335,
454,
358,
506,
7120,
18,
12279,
1147,
382,
628,
1234,
18,
15330,
358,
1147,
382,
5683,
1758,
18,
968,
1147,
1182,
11013,
434,
1234,
18,
15330,
18,
9029,
1147,
1182,
3844,
1931,
18,
7903,
7778,
335,
454,
18,
2073,
309,
1147,
1182,
11013,
434,
1234,
18,
15330,
353,
18662,
18,
5783,
2831,
434,
14502,
353,
1399,
358,
866,
309,
14502,
1704,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7720,
14332,
1345,
1290,
1345,
12,
203,
3639,
3155,
774,
1345,
12521,
751,
745,
892,
7720,
751,
16,
203,
3639,
12738,
17711,
5049,
335,
454,
745,
892,
5210,
5049,
335,
454,
203,
565,
262,
1071,
8843,
429,
288,
203,
3639,
467,
654,
39,
3462,
12,
22270,
751,
18,
2316,
382,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
5210,
5049,
335,
454,
18,
2316,
382,
5683,
16,
7720,
751,
18,
8949,
382,
1769,
203,
203,
3639,
2254,
5034,
11013,
4649,
273,
467,
654,
39,
3462,
12,
22270,
751,
18,
2316,
1182,
2934,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
3639,
2254,
5034,
1147,
1182,
6275,
3705,
273,
11013,
4649,
397,
7720,
751,
18,
8949,
1182,
2930,
31,
203,
203,
3639,
467,
442,
9062,
280,
5049,
335,
454,
12,
2248,
58,
2602,
916,
67,
12845,
2871,
4685,
2934,
8837,
5049,
335,
454,
12,
13540,
5049,
335,
454,
1769,
203,
203,
3639,
2254,
5034,
11013,
4436,
273,
467,
654,
39,
3462,
12,
22270,
751,
18,
2316,
1182,
2934,
12296,
951,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
309,
261,
12296,
4436,
411,
1147,
1182,
6275,
3705,
13,
288,
203,
5411,
15226,
22085,
11339,
1447,
6275,
12,
2316,
1182,
6275,
3705,
300,
11013,
4436,
16,
7720,
751,
18,
8949,
1182,
2930,
1769,
203,
3639,
289,
203,
3639,
309,
261,
22270,
751,
18,
7329,
330,
3840,
473,
374,
21718,
480,
374,
92,
20,
13,
288,
203,
5411,
1758,
7103,
330,
3840,
273,
7103,
15700,
815,
63,
22270,
751,
18,
7329,
330,
3840,
1671,
374,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol';
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./libraries/TransferHelper.sol";
import "./interfaces/IDPexFeeAggregator.sol";
import "./interfaces/IDPexRouter.sol";
import "./abstracts/Governable.sol";
import "./abstracts/SafeGas.sol";
contract DPexFeeAggregator is IDPexFeeAggregator, Initializable, ContextUpgradeable,
ReentrancyGuardUpgradeable, Governable, SafeGas {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
using EnumerableSet for EnumerableSet.AddressSet;
struct RewardSnapshot {
uint256 time;
uint256 totalPSI;
mapping(address => uint256) userRewards;
}
//== Variables ==
EnumerableSet.AddressSet private _feeTokens; // all the token where a fee is deducted from on swap
EnumerableSet.AddressSet private _tokenHolders; // all the tokens holder who will retrieve a share of fees
mapping(address => uint256) private _claimed; // total amount of psi claimed by a user
/**
* @notice psi token contract
*/
address public psi;
/**
* @notice psi token contract
*/
address public WETH;
/**
* @notice percentage which get deducted from a swap (1 = 0.1%)
*/
uint256 public dpexFee;
/**
* @notice token fees gathered in the current period
*/
mapping(address => uint256) public tokensGathered;
/**
* @notice returns the latest reward snapshot id
*/
uint public latestRewardSnapshotId;
/**
* @notice all user reward snapshots taken
*/
mapping (uint => RewardSnapshot) public rewardSnapshots;
//== CONSTRUCTOR ==
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
function initialize(address _gov_contract, address _WETH, address _psi) public initializer {
__Context_init();
__ReentrancyGuard_init();
super.initialize(_gov_contract);
dpexFee = 1;
latestRewardSnapshotId = 0;
psi = _psi;
WETH = _WETH;
}
//== MODIFIERS ==
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'DPexFeeAggregator: EXPIRED');
_;
}
modifier onlyRouter() {
require(router() == _msgSender(), "DPexFeeAggregator: ONLY_ROUTER_ALLOWED");
_;
}
//== VIEW ==
/**
* @notice check if the current user is an token holder
*/
function isTokenHolder(address user) public override view returns (bool) {
return _tokenHolders.contains(user);
}
/**
* @notice return all the tokens where a fee is deducted from on swap
*/
function feeTokens() external override view returns (address[] memory) {
address[] memory tokens = new address[](_feeTokens.length());
for(uint256 idx = 0; idx < _feeTokens.length(); idx++) {
tokens[idx] = _feeTokens.at(idx);
}
return tokens;
}
/**
* @notice checks if the token is a token where a fee is deducted from on swap
* @param token fee token to check
*/
function isFeeToken(address token) public override view returns (bool) {
return _feeTokens.contains(token);
}
/**
* @notice returns the fee for the amount given
* @param amount amount to calculate the fee for
*/
function calculateFee(uint256 amount) public override view returns (uint256 fee, uint256 amountLeft) {
amountLeft = (amount.mul(1000).sub(amount.mul(dpexFee))).div(1000);
fee = amount.sub(amountLeft);
}
/**
* @notice returns the fee for the amount given, but only if the token is in the feetokens list
* @param token token to check if it exists in the feetokens list
* @param amount amount to calculate the fee for
*/
function calculateFee(address token, uint256 amount) external override view
returns (uint256 fee, uint256 amountLeft) {
if (!_feeTokens.contains(token)) { return (0, amount); }
return calculateFee(amount);
}
/**
* @notice returns the time and totalPSI from a snapshot
* @param snapshotId the id from the snapshot to retrieve
*/
function getSnapshot(uint256 snapshotId) external override view returns (uint256 time, uint256 totalPsi) {
require(snapshotId > 0 && snapshotId <= latestRewardSnapshotId, "DPexFeeAggregator: INVALID_SNAPSHOT_ID");
require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET");
time = rewardSnapshots[snapshotId].time;
totalPsi = rewardSnapshots[snapshotId].totalPSI;
}
/**
* @notice returns the rewards for a user from a snapshot
* @param snapshotId the id from the snapshot to retrieve
* @param user the address from the user to check rewards for
*/
function getSnapshotRewards(uint256 snapshotId, address user) external override view returns (uint256 rewards) {
require(snapshotId > 0 && snapshotId <= latestRewardSnapshotId, "DPexFeeAggregator: INVALID_SNAPSHOT_ID");
require(user != address(0), "DPexFeeAggregator: NO_ADDRESS");
require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET");
rewards = rewardSnapshots[snapshotId].userRewards[user];
}
/**
* @notice returns the rewards for a user from a snapshot
* @param user the address from the user to check rewards for
*/
function getTotalRewards(address user) public override view returns (uint256 rewards) {
require(user != address(0), "DPexFeeAggregator: NO_ADDRESS");
require(latestRewardSnapshotId > 0, "DPexFeeAggregator: NO_SNAPSHOT_TAKEN_YET");
for(uint256 id = 1; id <= latestRewardSnapshotId; id++) {
rewards += rewardSnapshots[id].userRewards[user];
}
}
/**
* @notice returns the unclaimed rewards for a user from a snapshot
* @param user the address from the user to check rewards for
*/
function getUnclaimedRewards(address user) public override view returns (uint256 rewards) {
rewards = getTotalRewards(user).sub(_claimed[user]);
}
/**
* @notice returns the claimed rewards for a user from a snapshot
* @param user the address from the user to check rewards for
*/
function getClaimedRewards(address user) external override view returns (uint256 rewards) {
rewards =_claimed[user];
}
//== SET INTERNAL VARIABLES==
/**
* @notice adds a new token holder
* @param user address of the token holder
*/
function addTokenHolder(address user) external override {
require(user != address(0), "DPexFeeAggregator: TOKENHOLDER_NO_ADDRESS");
require(!isTokenHolder(user), "DPexFeeAggregator: ALREADY_TOKENHOLDER");
_tokenHolders.add(user);
}
/**
* @notice removes the msg_sender token holder
*/
function removeTokenHolder() external override {
require(isTokenHolder(_msgSender()), "DPexFeeAggregator: NOT_A_TOKENHOLDER");
_tokenHolders.remove(_msgSender());
}
/**
* @notice removes a token holder
* @param user address of the token holder
*/
function removeTokenHolder(address user) external override onlyGovernor {
require(user != address(0), "DPexFeeAggregator: TOKENHOLDER_NO_ADDRESS");
require(isTokenHolder(user), "DPexFeeAggregator: NOT_A_TOKENHOLDER");
_tokenHolders.remove(user);
}
/**
* @notice add a token to deduct a fee for on swap
* @param token fee token to add
*/
function addFeeToken(address token) public override onlyGovernor {
require(!_feeTokens.contains(token), "DPexFeeAggregator: ALREADY_FEE_TOKEN");
_feeTokens.add(token);
IERC20(token).approve(router(), 1e18);
}
/**
* @notice remove a token to deduct a fee for on swap
* @param token fee token to add
*/
function removeFeeToken(address token) external override onlyGovernor {
require(_feeTokens.contains(token), "DPexFeeAggregator: NO_FEE_TOKEN");
_feeTokens.remove(token);
}
/**
* @notice set the percentage which get deducted from a swap (1 = 0.1%)
* @param fee percentage to set as fee
*/
function setDPexFee(uint256 fee) external override onlyGovernor {
require(fee >= 0 && fee <= 200, "DPexFeeAggregator: FEE_MIN_0_MAX_20");
dpexFee = fee;
}
/**
* @notice Adds the fee to the tokensGathered list. Transfer is done in the router
* @param token fee token to check
* @param fee fee to add to the tokensGathered list
*/
function addTokenFee(address token, uint256 fee) external override onlyRouter {
require (_feeTokens.contains(token), "Token is not a feeToken");
tokensGathered[token] += fee;
}
/**
* @notice takes a snapshot of the current moment and transfer non PSI token to PSI
*/
function takeSnapshotWithRewards(uint256 deadline) external override useCHI onlyGovernor ensure(deadline) {
uint256 psiBalanceBefore = IERC20(psi).balanceOf(address(this));
sellFeesToPSI();
uint256 psiFeeBalance = IERC20(psi).balanceOf(address(this)).sub(psiBalanceBefore);
if (tokensGathered[psi] > 0) {
psiFeeBalance += tokensGathered[psi];
tokensGathered[psi] = 0;
}
uint256 totalPSIFromHolders = 0;
for(uint256 idx = 0; idx < _tokenHolders.length(); idx++) {
totalPSIFromHolders += IERC20(psi).balanceOf(_tokenHolders.at(idx));
}
latestRewardSnapshotId++;
rewardSnapshots[latestRewardSnapshotId].time = block.timestamp;
rewardSnapshots[latestRewardSnapshotId].totalPSI = psiFeeBalance;
for(uint256 idx = 0; idx < _tokenHolders.length(); idx++) {
uint256 userReward = psiFeeBalance.div(totalPSIFromHolders
.div(IERC20(psi).balanceOf(_tokenHolders.at(idx))));
if (userReward > 0) {
rewardSnapshots[latestRewardSnapshotId].userRewards[_tokenHolders.at(idx)] = userReward;
}
}
}
function sellFeesToPSI() internal {
for(uint256 idx = 0; idx < _feeTokens.length(); idx++) {
address token = _feeTokens.at(idx);
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
if (token != WETH && token != psi && tokenBalance > 0) {
tokensGathered[token] = 0;
address[] memory path = new address[](2);
path[0] = token;
path[1] = WETH;
IDPexRouter(router()).swapAggregatorToken(tokenBalance, path, address(this));
}
}
sellWETHToPSI();
}
function sellWETHToPSI() internal {
uint256 balance = IERC20(WETH).balanceOf(address(this));
if (balance <= 0) { return; }
tokensGathered[WETH] = 0;
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = psi;
IDPexRouter(router()).swapAggregatorToken(balance, path, address(this));
}
/**
* @notice Claims the rewards for a user
*/
function claim() external override nonReentrant useCHI {
uint256 rewards = getUnclaimedRewards(_msgSender());
require (rewards > 0, "DPexFeeAggregator: NO_REWARDS_TO_CLAIM");
_claimed[_msgSender()] += rewards;
IERC20(psi).safeTransfer(msg.sender, rewards);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// 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];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// 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 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IDPexFeeAggregator {
function isTokenHolder(address user) external view returns (bool);
function feeTokens() external view returns (address[] memory);
function isFeeToken(address token) external view returns (bool);
function calculateFee(uint256 amount) external view returns (uint256 fee, uint256 amountLeft);
function calculateFee(address token, uint256 amount) external view returns (uint256 fee, uint256 amountLeft);
function getSnapshot(uint256 snapshotId) external view returns (uint256 time, uint256 totalPsi);
function getSnapshotRewards(uint256 snapshotId, address user) external view returns (uint256 rewards);
function getTotalRewards(address user) external view returns (uint256 rewards);
function getUnclaimedRewards(address user) external view returns (uint256 rewards);
function getClaimedRewards(address user) external view returns (uint256 rewards);
function addTokenHolder(address user) external;
function removeTokenHolder() external;
function removeTokenHolder(address user) external;
function addFeeToken(address token) external;
function removeFeeToken(address token) external;
function setDPexFee(uint256 fee) external;
function addTokenFee(address token, uint256 fee) external;
function takeSnapshotWithRewards(uint256 deadline) external;
function claim() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./uniswap/IUniswapV2Router02.sol";
import "./IGovernable.sol";
interface IDPexRouter is IUniswapV2Router02, IGovernable {
function feeAggregator() external returns (address);
function setfeeAggregator(address aggregator) external;
function swapAggregatorToken(
uint amountIn,
address[] calldata path,
address to
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IGovernable.sol";
abstract contract Governable is ContextUpgradeable, IGovernable {
using Address for address;
//== Variables ==
address public gov_contract; // contract governing the Token
//== CONSTRUCTOR ==
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
function initialize(address _gov_contract) internal virtual {
require (_gov_contract.isContract(), "_gov_contract should be a contract");
gov_contract = _gov_contract;
}
//== MODIFIERS ==
modifier onlyMastermind() {
require(isMastermind(_msgSender()), "Only mastermind is allowed");
_;
}
modifier onlyGovernor() {
require(isGovernor(_msgSender()), "Only governor is allowed");
_;
}
modifier onlyPartner() {
require(isPartner(_msgSender()), "Only partner is allowed");
_;
}
//== VIEW ==
function isMastermind(address _address) public override view returns (bool) {
return IGovernable(gov_contract).isMastermind(_address);
}
function isGovernor(address _address) public override view returns (bool) {
return IGovernable(gov_contract).isGovernor(_address);
}
function isPartner(address _address) public override view returns (bool) {
return IGovernable(gov_contract).isPartner(_address);
}
function isUser(address _address) external override view returns (bool) {
return IGovernable(gov_contract).isUser(_address);
}
function gasToken() public override view returns (address) {
return IGovernable(gov_contract).gasToken();
}
function enableGasPromotion() public override view returns (bool) {
return IGovernable(gov_contract).enableGasPromotion();
}
function router() public override view returns (address) {
return IGovernable(gov_contract).router();
}
//== SET INTERNAL VARIABLES==
/**
* @dev Change the governance contract
* only mastermind is allowed to do this
* @param _gov_contract Governance contract address
*/
function setGovernanceContract(address _gov_contract) external onlyMastermind {
require(_gov_contract.isContract(), "_gov_contract should be a contract");
gov_contract = _gov_contract;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/ICHI.sol";
import "./Governable.sol";
abstract contract SafeGas is Governable {
/**
* @notice frees CHI from gas provider to reduce gas costs
* @dev requires that gas provider has approved this contract to use their CHI
*/
modifier useCHI {
uint256 gasStart = gasleft();
_;
//uint256 gasSpent = 21000 + gasStart - gasleft() + (16 * msg.data.length);
if (gasToken() != address(0)) {
ICHI(gasToken()).freeFromUpTo(ensureGasProvider(),
((21000 + gasStart - gasleft() + (16 * msg.data.length)) + 14154) / 41947);
}
}
/**
* @notice make it possible to add a single gas provider
*/
function ensureGasProvider() internal view returns (address) {
if (enableGasPromotion() && IERC20(gasToken()).balanceOf(address(this)) >= 1) {
return address(this);
}
return msg.sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IUniswapV2Router01.sol";
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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IGovernable {
function gasToken() external view returns (address);
function enableGasPromotion() external view returns (bool);
function router() external view returns (address);
function isMastermind(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isPartner(address _address) external view returns (bool);
function isUser(address _address) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IUniswapV2Router01 {
function factory() external returns (address);
function WETH() external 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 view returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external view 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);
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ICHI is IERC20 {
function freeFromUpTo(address _addr, uint256 _amount) external returns (uint256);
} | total amount of psi claimed by a user
| mapping(address => uint256) private _claimed; | 5,915,904 | [
1,
4963,
3844,
434,
23921,
7516,
329,
635,
279,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
14784,
329,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol";
import "./TokenStaking.sol";
import "./cryptography/BLS.sol";
import "./utils/AddressArrayUtils.sol";
import "./utils/PercentUtils.sol";
import "./libraries/operator/GroupSelection.sol";
import "./libraries/operator/Groups.sol";
import "./libraries/operator/DKGResultVerification.sol";
import "./libraries/operator/Reimbursements.sol";
interface ServiceContract {
function entryCreated(uint256 requestId, bytes calldata entry, address payable submitter) external;
function fundRequestSubsidyFeePool() external payable;
function fundDkgFeePool() external payable;
}
/**
* @title KeepRandomBeaconOperator
* @dev Keep client facing contract for random beacon security-critical operations.
* Handles group creation and expiration, BLS signature verification and incentives.
* The contract is not upgradeable. New functionality can be implemented by deploying
* new versions following Keep client update and re-authorization by the stakers.
*/
contract KeepRandomBeaconOperator is ReentrancyGuard {
using SafeMath for uint256;
using PercentUtils for uint256;
using AddressArrayUtils for address[];
using GroupSelection for GroupSelection.Storage;
using Groups for Groups.Storage;
using DKGResultVerification for DKGResultVerification.Storage;
event OnGroupRegistered(bytes groupPubKey);
event DkgResultSubmittedEvent(
uint256 memberIndex,
bytes groupPubKey,
bytes misbehaved
);
event RelayEntryRequested(bytes previousEntry, bytes groupPublicKey);
event RelayEntrySubmitted();
event GroupSelectionStarted(uint256 newEntry);
event GroupMemberRewardsWithdrawn(address indexed beneficiary, address operator, uint256 amount, uint256 groupIndex);
event RelayEntryTimeoutReported(uint256 indexed groupIndex);
event UnauthorizedSigningReported(uint256 indexed groupIndex);
GroupSelection.Storage groupSelection;
Groups.Storage groups;
DKGResultVerification.Storage dkgResultVerification;
// Contract owner.
address internal owner;
address[] internal serviceContracts;
// TODO: replace with a secure authorization protocol (addressed in RFC 11).
TokenStaking internal stakingContract;
// Each signing group member reward expressed in wei.
uint256 public groupMemberBaseReward = 145*1e11; // 14500 Gwei, 10% of operational cost
// Gas price ceiling value used to calculate the gas price for reimbursement
// next to the actual gas price from the transaction. We use gas price
// ceiling to defend against malicious miner-submitters who can manipulate
// transaction gas price.
uint256 public gasPriceCeiling = 30*1e9; // (30 Gwei = 30 * 10^9 wei)
// Size of a group in the threshold relay.
uint256 public groupSize = 64;
// Minimum number of group members needed to interact according to the
// protocol to produce a relay entry.
uint256 public groupThreshold = 33;
// Time in blocks after which the next group member is eligible
// to submit the result.
uint256 public resultPublicationBlockStep = 3;
// Timeout in blocks for a relay entry to appear on the chain. Blocks are
// counted from the moment relay request occur.
//
// Timeout is never shorter than the time needed by clients to generate
// relay entry and the time it takes for the last group member to become
// eligible to submit the result plus at least one block to submit it.
uint256 public relayEntryTimeout = groupSize.mul(resultPublicationBlockStep);
// Gas required to verify BLS signature and produce successful relay
// entry. Excludes callback and DKG gas. The worst case (most expensive)
// scenario.
uint256 public entryVerificationGasEstimate = 280000;
// Gas required to submit DKG result. Excludes initiation of group selection.
uint256 public dkgGasEstimate = 1740000;
// Gas required to trigger DKG (starting group selection).
uint256 public groupSelectionGasEstimate = 200000;
// Reimbursement for the submitter of the DKG result. This value is set when
// a new DKG request comes to the operator contract.
//
// When submitting DKG result, the submitter is reimbursed with the actual cost
// and some part of the fee stored in this field may be returned to the service
// contract.
uint256 public dkgSubmitterReimbursementFee;
uint256 internal currentEntryStartBlock;
// Seed value used for the genesis group selection.
// https://www.wolframalpha.com/input/?i=pi+to+78+digits
uint256 internal constant _genesisGroupSeed = 31415926535897932384626433832795028841971693993751058209749445923078164062862;
// Service contract that triggered current group selection.
ServiceContract internal groupSelectionStarterContract;
struct SigningRequest {
uint256 relayRequestId;
uint256 entryVerificationAndProfitFee;
uint256 callbackFee;
uint256 groupIndex;
bytes previousEntry;
address serviceContract;
}
SigningRequest internal signingRequest;
/**
* @dev Triggers the first group selection. Genesis can be called only when
* there are no groups on the operator contract.
*/
function genesis() public payable {
require(numberOfGroups() == 0, "Groups exist");
// Set latest added service contract as a group selection starter to receive any DKG fee surplus.
groupSelectionStarterContract = ServiceContract(serviceContracts[serviceContracts.length.sub(1)]);
startGroupSelection(_genesisGroupSeed, msg.value);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner == msg.sender, "Caller is not the owner");
_;
}
/**
* @dev Checks if sender is authorized.
*/
modifier onlyServiceContract() {
require(
serviceContracts.contains(msg.sender),
"Caller is not an authorized contract"
);
_;
}
constructor(address _serviceContract, address _stakingContract) public {
owner = msg.sender;
serviceContracts.push(_serviceContract);
stakingContract = TokenStaking(_stakingContract);
groups.stakingContract = TokenStaking(_stakingContract);
groups.groupActiveTime = TokenStaking(_stakingContract).undelegationPeriod();
// There are 39 blocks to submit group selection tickets. To minimize
// the submitter's cost by minimizing the number of redundant tickets
// that are not selected into the group, the following approach is
// recommended:
//
// Tickets are submitted in 11 rounds, each round taking 3 blocks.
// As the basic principle, the number of leading zeros in the ticket
// value is subtracted from the number of rounds to determine the round
// the ticket should be submitted in:
// - in round 0, tickets with 11 or more leading zeros are submitted
// - in round 1, tickets with 10 or more leading zeros are submitted
// (...)
// - in round 11, tickets with no leading zeros are submitted.
//
// In each round, group member candidate needs to monitor tickets
// submitted by other candidates and compare them against tickets of
// the candidate not yet submitted to determine if continuing with
// ticket submission still makes sense.
//
// After 33 blocks, there is a 6 blocks mining lag allowing all
// outstanding ticket submissions to have a higher chance of being
// mined before the deadline.
groupSelection.ticketSubmissionTimeout = 3 * 11 + 6;
groupSelection.groupSize = groupSize;
dkgResultVerification.timeDKG = 5*(1+5) + 2*(1+10) + 20;
dkgResultVerification.resultPublicationBlockStep = resultPublicationBlockStep;
dkgResultVerification.groupSize = groupSize;
// TODO: For now, the required number of signatures is equal to group
// threshold. This should be updated to keep a safety margin for
// participants misbehaving during signing.
dkgResultVerification.signatureThreshold = groupThreshold;
}
/**
* @dev Adds service contract
* @param serviceContract Address of the service contract.
*/
function addServiceContract(address serviceContract) public onlyOwner {
serviceContracts.push(serviceContract);
}
/**
* @dev Removes service contract
* @param serviceContract Address of the service contract.
*/
function removeServiceContract(address serviceContract) public onlyOwner {
serviceContracts.removeAddress(serviceContract);
}
/**
* @dev Triggers the selection process of a new candidate group.
* @param _newEntry New random beacon value that stakers will use to
* generate their tickets.
* @param submitter Operator of this contract.
*/
function createGroup(uint256 _newEntry, address payable submitter) public payable onlyServiceContract {
uint256 groupSelectionStartFee = groupSelectionGasEstimate.mul(gasPriceCeiling);
groupSelectionStarterContract = ServiceContract(msg.sender);
startGroupSelection(_newEntry, msg.value.sub(groupSelectionStartFee));
// reimbursing a submitter that triggered group selection
(bool success, ) = stakingContract.magpieOf(submitter).call.value(groupSelectionStartFee)("");
require(success, "Failed reimbursing submitter for starting a group selection");
}
function startGroupSelection(uint256 _newEntry, uint256 _payment) internal {
require(
_payment >= gasPriceCeiling.mul(dkgGasEstimate),
"Insufficient DKG fee"
);
require(isGroupSelectionPossible(), "Group selection in progress");
// If previous group selection failed and there is reimbursement left
// return it to the DKG fee pool.
if (dkgSubmitterReimbursementFee > 0) {
uint256 surplus = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
ServiceContract(msg.sender).fundDkgFeePool.value(surplus)();
}
groupSelection.minimumStake = stakingContract.minimumStake();
groupSelection.start(_newEntry);
emit GroupSelectionStarted(_newEntry);
dkgSubmitterReimbursementFee = _payment;
}
function isGroupSelectionPossible() public view returns (bool) {
if (!groupSelection.inProgress) {
return true;
}
// dkgTimeout is the time after key generation protocol is expected to
// be complete plus the expected time to submit the result.
uint256 dkgTimeout = groupSelection.ticketSubmissionStartBlock +
groupSelection.ticketSubmissionTimeout +
dkgResultVerification.timeDKG +
groupSize * resultPublicationBlockStep;
return block.number > dkgTimeout;
}
/**
* @dev Submits ticket to request to participate in a new candidate group.
* @param ticket Bytes representation of a ticket that holds the following:
* - ticketValue: first 8 bytes of a result of keccak256 cryptography hash
* function on the combination of the group selection seed (previous
* beacon output), staker-specific value (address) and virtual staker index.
* - stakerValue: a staker-specific value which is the address of the staker.
* - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight;
* has to be unique for all tickets submitted by the given staker for the
* current candidate group selection.
*/
function submitTicket(bytes32 ticket) public {
uint256 stakingWeight = stakingContract.eligibleStake(msg.sender, address(this)).div(groupSelection.minimumStake);
groupSelection.submitTicket(ticket, stakingWeight);
}
/**
* @dev Gets the timeout in blocks after which group candidate ticket
* submission is finished.
*/
function ticketSubmissionTimeout() public view returns (uint256) {
return groupSelection.ticketSubmissionTimeout;
}
/**
* @dev Gets the submitted group candidate tickets so far.
*/
function submittedTickets() public view returns (uint64[] memory) {
return groupSelection.tickets;
}
/**
* @dev Gets selected participants in ascending order of their tickets.
*/
function selectedParticipants() public view returns (address[] memory) {
return groupSelection.selectedParticipants();
}
/**
* @dev Submits result of DKG protocol. It is on-chain part of phase 14 of
* the protocol.
*
* @param submitterMemberIndex Claimed submitter candidate group member index
* @param groupPubKey Generated candidate group public key
* @param misbehaved Bytes array of misbehaved (disqualified or inactive)
* group members indexes in ascending order; Indexes reflect positions of
* members in the group as outputted by the group selection protocol.
* @param signatures Concatenation of signatures from members supporting the
* result.
* @param signingMembersIndexes Indices of members corresponding to each
* signature.
*/
function submitDkgResult(
uint256 submitterMemberIndex,
bytes memory groupPubKey,
bytes memory misbehaved,
bytes memory signatures,
uint[] memory signingMembersIndexes
) public {
address[] memory members = selectedParticipants();
dkgResultVerification.verify(
submitterMemberIndex,
groupPubKey,
misbehaved,
signatures,
signingMembersIndexes,
members,
groupSelection.ticketSubmissionStartBlock + groupSelection.ticketSubmissionTimeout
);
groups.setGroupMembers(groupPubKey, members, misbehaved);
groups.addGroup(groupPubKey);
reimburseDkgSubmitter();
emit DkgResultSubmittedEvent(submitterMemberIndex, groupPubKey, misbehaved);
groupSelection.stop();
}
/**
* @dev Compare the reimbursement fee calculated based on the current transaction gas
* price and the current price feed estimate with the DKG reimbursement fee calculated
* and paid at the moment when the DKG was requested. If there is any surplus, it will
* be returned to the DKG fee pool of the service contract which triggered the DKG.
*/
function reimburseDkgSubmitter() internal {
uint256 gasPrice = gasPriceCeiling;
// We need to check if tx.gasprice is non-zero as a workaround to a bug
// in go-ethereum:
// https://github.com/ethereum/go-ethereum/pull/20189
if (tx.gasprice > 0 && tx.gasprice < gasPriceCeiling) {
gasPrice = tx.gasprice;
}
uint256 reimbursementFee = dkgGasEstimate.mul(gasPrice);
address payable magpie = stakingContract.magpieOf(msg.sender);
if (reimbursementFee < dkgSubmitterReimbursementFee) {
uint256 surplus = dkgSubmitterReimbursementFee.sub(reimbursementFee);
dkgSubmitterReimbursementFee = 0;
// Reimburse submitter with actual DKG cost.
magpie.call.value(reimbursementFee)("");
// Return surplus to the contract that started DKG.
groupSelectionStarterContract.fundDkgFeePool.value(surplus)();
} else {
// If submitter used higher gas price reimburse only dkgSubmitterReimbursementFee max.
reimbursementFee = dkgSubmitterReimbursementFee;
dkgSubmitterReimbursementFee = 0;
magpie.call.value(reimbursementFee)("");
}
}
/**
* @dev Creates a request to generate a new relay entry, which will include a
* random number (by signing the previous entry's random number).
* @param requestId Request Id trackable by service contract
* @param previousEntry Previous relay entry
*/
function sign(
uint256 requestId,
bytes memory previousEntry
) public payable onlyServiceContract {
uint256 entryVerificationAndProfitFee = groupProfitFee().add(
entryVerificationFee()
);
require(
msg.value >= entryVerificationAndProfitFee,
"Insufficient new entry fee"
);
uint256 callbackFee = msg.value.sub(entryVerificationAndProfitFee);
signRelayEntry(
requestId, previousEntry, msg.sender,
entryVerificationAndProfitFee, callbackFee
);
}
function signRelayEntry(
uint256 requestId,
bytes memory previousEntry,
address serviceContract,
uint256 entryVerificationAndProfitFee,
uint256 callbackFee
) internal {
require(!isEntryInProgress() || hasEntryTimedOut(), "Beacon is busy");
currentEntryStartBlock = block.number;
uint256 groupIndex = groups.selectGroup(uint256(keccak256(previousEntry)));
signingRequest = SigningRequest(
requestId,
entryVerificationAndProfitFee,
callbackFee,
groupIndex,
previousEntry,
serviceContract
);
bytes memory groupPubKey = groups.getGroupPublicKey(groupIndex);
emit RelayEntryRequested(previousEntry, groupPubKey);
}
/**
* @dev Creates a new relay entry and stores the associated data on the chain.
* @param _groupSignature Group BLS signature over the concatenation of the
* previous entry and seed.
*/
function relayEntry(bytes memory _groupSignature) public nonReentrant {
require(isEntryInProgress(), "Entry was submitted");
require(!hasEntryTimedOut(), "Entry timed out");
bytes memory groupPubKey = groups.getGroupPublicKey(signingRequest.groupIndex);
require(
BLS.verify(
groupPubKey,
signingRequest.previousEntry,
_groupSignature
),
"Invalid signature"
);
emit RelayEntrySubmitted();
// Spend no more than groupSelectionGasEstimate + 40000 gas max
// This will prevent relayEntry failure in case the service contract is compromised
signingRequest.serviceContract.call.gas(groupSelectionGasEstimate.add(40000))(
abi.encodeWithSignature(
"entryCreated(uint256,bytes,address)",
signingRequest.relayRequestId,
_groupSignature,
msg.sender
)
);
if (signingRequest.callbackFee > 0) {
executeCallback(signingRequest, uint256(keccak256(_groupSignature)));
}
(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) = newEntryRewardsBreakdown();
groups.addGroupMemberReward(groupPubKey, groupMemberReward);
stakingContract.magpieOf(msg.sender).call.value(submitterReward)("");
if (subsidy > 0) {
signingRequest.serviceContract.call.gas(35000).value(subsidy)(abi.encodeWithSignature("fundRequestSubsidyFeePool()"));
}
currentEntryStartBlock = 0;
}
/**
* @dev Executes customer specified callback for the relay entry request.
* @param signingRequest Request data tracked internally by this contract.
* @param entry The generated random number.
*/
function executeCallback(SigningRequest memory signingRequest, uint256 entry) internal {
uint256 callbackFee = signingRequest.callbackFee;
// Make sure not to spend more than what was received from the service
// contract for the callback
uint256 gasLimit = callbackFee.div(gasPriceCeiling);
bytes memory callbackReturnData;
uint256 gasBeforeCallback = gasleft();
(, callbackReturnData) = signingRequest.serviceContract.call.gas(
gasLimit
)(abi.encodeWithSignature(
"executeCallback(uint256,uint256)",
signingRequest.relayRequestId,
entry
));
uint256 gasAfterCallback = gasleft();
uint256 gasSpent = gasBeforeCallback.sub(gasAfterCallback);
Reimbursements.reimburseCallback(
stakingContract,
gasPriceCeiling,
gasLimit,
gasSpent,
callbackFee,
callbackReturnData
);
}
/**
* @dev Get rewards breakdown in wei for successful entry for the current signing request.
*/
function newEntryRewardsBreakdown() internal view returns(uint256 groupMemberReward, uint256 submitterReward, uint256 subsidy) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
uint256 delayFactor = getDelayFactor();
groupMemberReward = groupMemberBaseReward.mul(delayFactor).div(decimals);
// delay penalty = base reward * (1 - delay factor)
uint256 groupMemberDelayPenalty = groupMemberBaseReward.mul(decimals.sub(delayFactor));
// The submitter reward consists of:
// The callback gas expenditure (reimbursed by the service contract)
// The entry verification fee to cover the cost of verifying the submission,
// paid regardless of their gas expenditure
// Submitter extra reward - 5% of the delay penalties of the entire group
uint256 submitterExtraReward = groupMemberDelayPenalty.mul(groupSize).percent(5).div(decimals);
uint256 entryVerificationFee = signingRequest.entryVerificationAndProfitFee.sub(groupProfitFee());
submitterReward = entryVerificationFee.add(submitterExtraReward);
// Rewards not paid out to the operators are paid out to requesters to subsidize new requests.
subsidy = groupProfitFee().sub(groupMemberReward.mul(groupSize)).sub(submitterExtraReward);
}
/**
* @dev Gets delay factor for rewards calculation.
* @return Integer representing floating-point number with 16 decimals places.
*/
function getDelayFactor() internal view returns(uint256 delayFactor) {
uint256 decimals = 1e16; // Adding 16 decimals to perform float division.
// T_deadline is the earliest block when no submissions are accepted
// and an entry timed out. The last block the entry can be published in is
// currentEntryStartBlock + relayEntryTimeout
// and submission are no longer accepted from block
// currentEntryStartBlock + relayEntryTimeout + 1.
uint256 deadlineBlock = currentEntryStartBlock.add(relayEntryTimeout).add(1);
// T_begin is the earliest block the result can be published in.
// Relay entry can be generated instantly after relay request is
// registered on-chain so a new entry can be published at the next
// block the earliest.
uint256 submissionStartBlock = currentEntryStartBlock.add(1);
// Use submissionStartBlock block as entryReceivedBlock if entry submitted earlier than expected.
uint256 entryReceivedBlock = block.number <= submissionStartBlock ? submissionStartBlock:block.number;
// T_remaining = T_deadline - T_received
uint256 remainingBlocks = deadlineBlock.sub(entryReceivedBlock);
// T_deadline - T_begin
uint256 submissionWindow = deadlineBlock.sub(submissionStartBlock);
// delay factor = [ T_remaining / (T_deadline - T_begin)]^2
//
// Since we add 16 decimal places to perform float division, we do:
// delay factor = [ T_temaining * decimals / (T_deadline - T_begin)]^2 / decimals =
// = [T_remaining / (T_deadline - T_begin) ]^2 * decimals
delayFactor = ((remainingBlocks.mul(decimals).div(submissionWindow))**2).div(decimals);
}
/**
* @dev Returns true if generation of a new relay entry is currently in
* progress.
*/
function isEntryInProgress() internal view returns (bool) {
return currentEntryStartBlock != 0;
}
/**
* @dev Returns true if the currently ongoing new relay entry generation
* operation timed out. There is a certain timeout for a new relay entry
* to be produced, see `relayEntryTimeout` value.
*/
function hasEntryTimedOut() internal view returns (bool) {
return currentEntryStartBlock != 0 && block.number > currentEntryStartBlock + relayEntryTimeout;
}
/**
* @dev Function used to inform about the fact the currently ongoing
* new relay entry generation operation timed out. As a result, the group
* which was supposed to produce a new relay entry is immediately
* terminated and a new group is selected to produce a new relay entry.
* All members of the group are punished by seizing minimum stake of
* their tokens. The submitter of the transaction is rewarded with a
* tattletale reward which is limited to min(1, 20 / group_size) of the
* maximum tattletale reward.
*/
function reportRelayEntryTimeout() public {
require(hasEntryTimedOut(), "Entry did not time out");
uint256 minimumStake = stakingContract.minimumStake();
groups.reportRelayEntryTimeout(signingRequest.groupIndex, groupSize, minimumStake);
// We could terminate the last active group. If that's the case,
// do not try to execute signing again because there is no group
// which can handle it.
if (numberOfGroups() > 0) {
signRelayEntry(
signingRequest.relayRequestId,
signingRequest.previousEntry,
signingRequest.serviceContract,
signingRequest.entryVerificationAndProfitFee,
signingRequest.callbackFee
);
}
emit RelayEntryTimeoutReported(signingRequest.groupIndex);
}
/**
* @dev Gets group profit fee expressed in wei.
*/
function groupProfitFee() public view returns(uint256) {
return groupMemberBaseReward.mul(groupSize);
}
/**
* @dev Checks if the specified account has enough active stake to become
* network operator and that this contract has been authorized for potential
* slashing.
*
* Having the required minimum of active stake makes the operator eligible
* to join the network. If the active stake is not currently undelegating,
* operator is also eligible for work selection.
*
* @param staker Staker's address
* @return True if has enough active stake to participate in the network,
* false otherwise.
*/
function hasMinimumStake(address staker) public view returns(bool) {
return stakingContract.hasMinimumStake(staker, address(this));
}
/**
* @dev Checks if group with the given public key is registered.
*/
function isGroupRegistered(bytes memory groupPubKey) public view returns(bool) {
return groups.isGroupRegistered(groupPubKey);
}
/**
* @dev Checks if a group with the given public key is a stale group.
* Stale group is an expired group which is no longer performing any
* operations. It is important to understand that an expired group may
* still perform some operations for which it was selected when it was still
* active. We consider a group to be stale when it's expired and when its
* expiration time and potentially executed operation timeout are both in
* the past.
*/
function isStaleGroup(bytes memory groupPubKey) public view returns(bool) {
return groups.isStaleGroup(groupPubKey);
}
/**
* @dev Gets the number of active groups. Expired and terminated groups are
* not counted as active.
*/
function numberOfGroups() public view returns(uint256) {
return groups.numberOfGroups();
}
/**
* @dev Returns accumulated group member rewards for provided group.
*/
function getGroupMemberRewards(bytes memory groupPubKey) public view returns (uint256) {
return groups.groupMemberRewards[groupPubKey];
}
/**
* @dev Gets all indices in the provided group for a member.
*/
function getGroupMemberIndices(bytes memory groupPubKey, address member) public view returns (uint256[] memory indices) {
return groups.getGroupMemberIndices(groupPubKey, member);
}
/**
* @dev Withdraws accumulated group member rewards for operator
* using the provided group index and member indices. Once the
* accumulated reward is withdrawn from the selected group, member is
* removed from it. Rewards can be withdrawn only from stale group.
* @param operator Operator address.
* @param groupIndex Group index.
* @param groupMemberIndices Array of member indices for the group member.
*/
function withdrawGroupMemberRewards(address operator, uint256 groupIndex, uint256[] memory groupMemberIndices) public nonReentrant {
uint256 accumulatedRewards = groups.withdrawFromGroup(operator, groupIndex, groupMemberIndices);
(bool success, ) = stakingContract.magpieOf(operator).call.value(accumulatedRewards)("");
if (success) {
emit GroupMemberRewardsWithdrawn(stakingContract.magpieOf(operator), operator, accumulatedRewards, groupIndex);
}
}
/**
* @dev Gets the index of the first active group.
*/
function getFirstActiveGroupIndex() public view returns (uint256) {
return groups.expiredGroupOffset;
}
/**
* @dev Gets group public key.
*/
function getGroupPublicKey(uint256 groupIndex) public view returns (bytes memory) {
return groups.getGroupPublicKey(groupIndex);
}
/**
* @dev Returns fee for entry verification in wei. Does not include group
* profit fee, DKG contribution or callback fee.
*/
function entryVerificationFee() public view returns (uint256) {
return entryVerificationGasEstimate.mul(gasPriceCeiling);
}
/**
* @dev Returns fee for group creation in wei. Includes the cost of DKG
* and the cost of triggering group selection.
*/
function groupCreationFee() public view returns (uint256) {
return dkgGasEstimate.add(groupSelectionGasEstimate).mul(gasPriceCeiling);
}
/**
* @dev Returns members of the given group by group public key.
*/
function getGroupMembers(bytes memory groupPubKey) public view returns (address[] memory members) {
return groups.getGroupMembers(groupPubKey);
}
/**
* @dev Reports unauthorized signing for the provided group. Must provide
* a valid signature of the tattletale address as a message. Successful signature
* verification means the private key has been leaked and all group members
* should be punished by seizing their tokens. The submitter of this proof is
* rewarded with 5% of the total seized amount scaled by the reward adjustment
* parameter and the rest 95% is burned.
*/
function reportUnauthorizedSigning(
uint256 groupIndex,
bytes memory signedMsgSender
) public {
uint256 minimumStake = stakingContract.minimumStake();
groups.reportUnauthorizedSigning(groupIndex, signedMsgSender, minimumStake);
emit UnauthorizedSigningReported(groupIndex);
}
}
| (30 Gwei = 30 * 10^9 wei)
| uint256 public gasPriceCeiling = 30*1e9; | 1,840,260 | [
1,
12,
5082,
611,
1814,
77,
273,
5196,
225,
1728,
66,
29,
732,
77,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
16189,
5147,
39,
73,
4973,
273,
5196,
14,
21,
73,
29,
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
] |
./full_match/1/0xB54e893f5D21Fc7554755b0b58B2d187bfFAe1f5/sources/contracts/token/RoboFiToken.sol | * @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin 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 RoboFiToken is Context, IRoboFiERC20, IInitializable {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string internal _name;
string internal _symbol;
constructor (string memory name_, string memory symbol_, uint256 initAmount_, address holder_) {
_name = name_;
_symbol = symbol_;
if (holder_ != address(0))
_mint(holder_, initAmount_);
}
function init(bytes calldata data) external virtual payable override {
require(_totalSupply == 0, "RT: contract is already initialized");
uint256 _initSupply;
address _holder;
(_name, _symbol, _initSupply, _holder) = abi.decode(data, (string, string, uint256, address));
if (_initSupply > 0)
_mint(_holder, _initSupply);
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "RT: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "RT: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "RT: transfer from the zero address");
require(recipient != address(0), "RT: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "RT: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
_afterTokenTransfer(sender, recipient, amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "RT: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "RT: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_internalBurn(account, amount);
_afterTokenTransfer(account, address(0), amount);
emit Transfer(account, address(0), amount);
}
function _internalBurn(address account, uint256 amount) internal {
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "RT: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
}
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "RT: approve from the zero address");
require(spender != address(0), "RT: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
| 16,525,796 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
9875,
14567,
30,
4186,
15226,
3560,
434,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
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,
19686,
83,
42,
77,
1345,
353,
1772,
16,
467,
14444,
83,
42,
77,
654,
39,
3462,
16,
467,
4435,
6934,
288,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
2713,
389,
529,
31,
203,
565,
533,
2713,
389,
7175,
31,
203,
203,
203,
565,
3885,
261,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
16,
2254,
5034,
1208,
6275,
67,
16,
1758,
10438,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
309,
261,
4505,
67,
480,
1758,
12,
20,
3719,
203,
5411,
389,
81,
474,
12,
4505,
67,
16,
1208,
6275,
67,
1769,
203,
565,
289,
203,
203,
565,
445,
1208,
12,
3890,
745,
892,
501,
13,
3903,
5024,
8843,
429,
3849,
288,
203,
3639,
2583,
24899,
4963,
3088,
1283,
422,
374,
16,
315,
12185,
30,
6835,
353,
1818,
6454,
8863,
203,
3639,
2254,
5034,
389,
2738,
3088,
1283,
31,
203,
3639,
1758,
389,
4505,
31,
203,
3639,
261,
67,
529,
16,
389,
7175,
16,
389,
2738,
3088,
1283,
16,
389,
4505,
13,
273,
24126,
18,
3922,
12,
892,
16,
261,
1080,
16,
533,
16,
2254,
5034,
16,
1758,
10019,
203,
3639,
309,
261,
67,
2738,
3088,
1283,
405,
374,
13,
203,
5411,
389,
81,
474,
24899,
4505,
16,
2
] |
pragma solidity ^0.4.17;
library SafeMathMod {// Partial SafeMath Library
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) < a);
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) > a);
}
}
contract YOLOCASH {//is inherently ERC20
using SafeMathMod for uint256;
/**
* @constant name The name of the token
* @constant symbol The symbol used to display the currency
* @constant decimals The number of decimals used to dispay a balance
* @constant totalSupply The total number of tokens times 10^ of the number of decimals
* @constant MAX_UINT256 Magic number for unlimited allowance
* @storage balanceOf Holds the balances of all token holders
* @storage allowed Holds the allowable balance to be transferable by another address.
*/
string constant public name = "YOLOCASH";
string constant public symbol = "YLC";
uint8 constant public decimals = 8;
uint256 constant public totalSupply = 43888888e8;
uint256 constant private MAX_UINT256 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowed;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event TransferFrom(address indexed _spender, address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function YOLOCASH() public {balanceOf[msg.sender] = totalSupply;}
/**
* @notice send `_value` token to `_to` from `msg.sender`
*
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
/* Ensures that tokens are not sent to address "0x0" */
require(_to != address(0));
/* Prevents sending tokens directly to contracts. */
require(isNotContract(_to));
/* SafeMathMOd.sub will throw if there is not enough balance and if the transfer value is 0. */
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value The amount of token to be transferred
* @return Whether the transfer was successful or not
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
/* Ensures that tokens are not sent to address "0x0" */
require(_to != address(0));
/* Ensures tokens are not sent to this contract */
require(_to != address(this));
uint256 allowance = allowed[_from][msg.sender];
/* Ensures sender has enough available allowance OR sender is balance holder allowing single transsaction send to contracts*/
require(_value <= allowance || _from == msg.sender);
/* Use SafeMathMod to add and subtract from the _to and _from addresses respectively. Prevents under/overflow and 0 transfers */
balanceOf[_to] = balanceOf[_to].add(_value);
balanceOf[_from] = balanceOf[_from].sub(_value);
/* Only reduce allowance if not MAX_UINT256 in order to save gas on unlimited allowance */
/* Balance holder does not need allowance to send from self. */
if (allowed[_from][msg.sender] != MAX_UINT256 && _from != msg.sender) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
}
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _toAddresses Receiver addresses.
* @param _amounts Amounts of tokens that will be transferred.
*/
function multiPartyTransfer(address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transfer(_toAddresses[i], _amounts[i]);
}
}
/**
* @dev Transfer the specified amounts of tokens to the specified addresses from authorized balance of sender.
* @dev Be aware that there is no check for duplicate recipients.
*
* @param _from The address of the sender
* @param _toAddresses The addresses of the recipients (MAX 255)
* @param _amounts The amounts of tokens to be transferred
*/
function multiPartyTransferFrom(address _from, address[] _toAddresses, uint256[] _amounts) public {
/* Ensures _toAddresses array is less than or equal to 255 */
require(_toAddresses.length <= 255);
/* Ensures _toAddress and _amounts have the same number of entries. */
require(_toAddresses.length == _amounts.length);
for (uint8 i = 0; i < _toAddresses.length; i++) {
transferFrom(_from, _toAddresses[i], _amounts[i]);
}
}
/**
* @notice `msg.sender` approves `_spender` to spend `_value` tokens
*
* @param _spender The address of the account able to transfer the tokens
* @param _value The amount of tokens to be approved for transfer
* @return Whether the approval was successful or not
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
/* Ensures address "0x0" is not assigned allowance. */
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @param _owner The address of the account owning tokens
* @param _spender The address of the account able to transfer the tokens
* @return Amount of remaining tokens allowed to spent
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
remaining = allowed[_owner][_spender];
}
function isNotContract(address _addr) private view returns (bool) {
uint length;
assembly {
/* retrieve the size of the code on target address, this needs assembly */
length := extcodesize(_addr)
}
return (length == 0);
}
// revert on eth transfers to this contract
function() public payable {revert();}
} | * @notice send `_value` token to `_to` from `msg.sender` @param _to The address of the recipient @param _value The amount of token to be transferred @return Whether the transfer was successful or not/ | function transfer(address _to, uint256 _value) public returns (bool success) {
require(_to != address(0));
require(isNotContract(_to));
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
function YOLOCASH() public {balanceOf[msg.sender] = totalSupply;}
}
| 8,046,806 | [
1,
4661,
1375,
67,
1132,
68,
1147,
358,
1375,
67,
869,
68,
628,
1375,
3576,
18,
15330,
68,
225,
389,
869,
1021,
1758,
434,
326,
8027,
225,
389,
1132,
1021,
3844,
434,
1147,
358,
506,
906,
4193,
327,
17403,
326,
7412,
1703,
6873,
578,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
24899,
869,
480,
1758,
12,
20,
10019,
203,
3639,
2583,
12,
291,
1248,
8924,
24899,
869,
10019,
203,
203,
3639,
11013,
951,
63,
3576,
18,
15330,
65,
273,
11013,
951,
63,
3576,
18,
15330,
8009,
1717,
24899,
1132,
1769,
203,
3639,
11013,
951,
63,
67,
869,
65,
273,
11013,
951,
63,
67,
869,
8009,
1289,
24899,
1132,
1769,
203,
3639,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
203,
565,
445,
1624,
51,
1502,
3587,
2664,
1435,
1071,
288,
12296,
951,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
97,
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
] |
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")
{}
}
| Stake to get vnfts min $muse amount required to stake amount of points needed to redeem a vnft, roughly 1 point is given each day; | contract StakeForVnfts is Roles {
using SafeMath for uint256;
IERC20 public museToken;
IERC721 public vNFT;
uint256 public minStake = 5 * 10**18;
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);
}
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;
}
_;
}
modifier updateReward(address account) {
if (account != address(0)) {
points[account] = earned(account);
lastUpdateTime[account] = block.timestamp;
}
_;
}
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"
);
totalStaked = totalStaked.add(_amount);
balance[msg.sender] = balance[msg.sender].add(_amount);
museToken.transferFrom(msg.sender, address(this), _amount);
emit Staked(msg.sender, _amount);
}
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);
museToken.transfer(msg.sender, amount);
emit Withdrawal(msg.sender, amount);
}
function exit() external {
withdraw(balance[msg.sender]);
}
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);
}
}
| 2,553,296 | [
1,
510,
911,
358,
336,
21732,
1222,
87,
1131,
271,
81,
1202,
3844,
1931,
358,
384,
911,
3844,
434,
3143,
3577,
358,
283,
24903,
279,
21732,
1222,
16,
23909,
715,
404,
1634,
353,
864,
1517,
2548,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
934,
911,
1290,
58,
82,
1222,
87,
353,
19576,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
654,
39,
3462,
1071,
312,
1202,
1345,
31,
203,
565,
467,
654,
39,
27,
5340,
1071,
331,
50,
4464,
31,
203,
203,
565,
2254,
5034,
1071,
1131,
510,
911,
273,
1381,
380,
1728,
636,
2643,
31,
203,
203,
565,
2254,
5034,
1071,
21732,
1222,
5147,
273,
1381,
380,
1728,
636,
2643,
31,
203,
565,
2254,
5034,
1071,
2078,
510,
9477,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
11013,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1142,
1891,
950,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
3143,
31,
203,
203,
565,
871,
934,
9477,
12,
2867,
10354,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
287,
12,
2867,
10354,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
776,
82,
1222,
49,
474,
329,
12,
2867,
358,
1769,
203,
203,
565,
871,
934,
911,
6113,
5033,
12,
11890,
5034,
394,
6275,
1769,
203,
565,
871,
20137,
951,
25031,
1222,
5033,
12,
11890,
5034,
394,
6275,
1769,
203,
203,
565,
3885,
12,
2867,
389,
90,
50,
4464,
16,
1758,
389,
81,
1202,
1345,
13,
1071,
288,
203,
3639,
331,
50,
4464,
273,
467,
654,
39,
27,
5340,
24899,
90,
50,
4464,
1769,
203,
3639,
312,
1202,
1345,
273,
467,
654,
39,
3462,
24899,
81,
1202,
1345,
1769,
203,
565,
289,
203,
203,
565,
445,
2549,
510,
911,
6113,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../interfaces/IOracle.sol";
// Chainlink Aggregator
interface ILPOracle {
function lp_price() external view returns (uint256 price);
}
contract ThreeCryptoOracle is IOracle {
ILPOracle constant public LP_ORACLE = ILPOracle(0xE8b2989276E2Ca8FDEA2268E3551b2b4B2418950);
// Calculates the lastest exchange rate
// Uses both divide and multiply only for tokens not supported directly by Chainlink, for example MKR/USD
function _get() internal view returns (uint256) {
return 1e36 / LP_ORACLE.lp_price();
}
// Get the latest exchange rate
/// @inheritdoc IOracle
function get(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the last exchange rate without any state changes
/// @inheritdoc IOracle
function peek(bytes calldata) public view override returns (bool, uint256) {
return (true, _get());
}
// Check the current spot exchange rate without any state changes
/// @inheritdoc IOracle
function peekSpot(bytes calldata data) external view override returns (uint256 rate) {
(, rate) = peek(data);
}
/// @inheritdoc IOracle
function name(bytes calldata) public pure override returns (string memory) {
return "3Crv";
}
/// @inheritdoc IOracle
function symbol(bytes calldata) public pure override returns (string memory) {
return "3crv";
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.12;
interface IOracle {
/// @notice Get the latest exchange rate.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function get(bytes calldata data) external returns (bool success, uint256 rate);
/// @notice Check the last exchange rate without any state changes.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return success if no valid (recent) rate is available, return false else true.
/// @return rate The rate of the requested asset / pair / pool.
function peek(bytes calldata data) external view returns (bool success, uint256 rate);
/// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek().
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return rate The rate of the requested asset / pair / pool.
function peekSpot(bytes calldata data) external view returns (uint256 rate);
/// @notice Returns a human readable (short) name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable symbol name about this oracle.
function symbol(bytes calldata data) external view returns (string memory);
/// @notice Returns a human readable name about this oracle.
/// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle.
/// For example:
/// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256));
/// @return (string) A human readable name about this oracle.
function name(bytes calldata data) external view returns (string memory);
}
| @inheritdoc IOracle | function name(bytes calldata) public pure override returns (string memory) {
return "3Crv";
}
| 13,997,627 | [
1,
36,
10093,
1665,
16873,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
508,
12,
3890,
745,
892,
13,
1071,
16618,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
23,
39,
4962,
14432,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
}
contract ClockAuctionBase {
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external;
function isSaleAuction() public returns (bool);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param _account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address _account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(_account) }
return size > 0;
}
}
contract CardBase is Ownable {
bytes4 constant InterfaceSignature_ERC165 = 0x01ffc9a7;
bytes4 constant InterfaceSignature_ERC721 = 0x80ac58cd;
bytes4 internal constant InterfaceId_ERC721Exists = 0x4f558e79;
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return (
(_interfaceID == InterfaceSignature_ERC165) ||
(_interfaceID == InterfaceSignature_ERC721) ||
(_interfaceID == InterfaceId_ERC721Exists)
);
}
}
contract CardMint is CardBase {
using AddressUtils for address;
/* EVENTS */
event TemplateMint(uint256 _templateId);
// Transfer from address 0x0 = newly minted card.
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
);
/* DATA TYPES */
struct Template {
uint256 generation;
uint256 category;
uint256 variation;
string name;
}
/* STORAGE */
// Minter address can mint cards but not templates.
address public minter;
Template[] internal templates;
// Each Card is a template ID (index of a template in `templates`).
uint256[] internal cards;
// Template ID => max number of cards that can be minted with this template ID.
mapping (uint256 => uint256) internal templateIdToMintLimit;
// Template ID => number of cards that have been minted with this template ID.
mapping (uint256 => uint256) internal templateIdToMintCount;
// Card ID => owner of card.
mapping (uint256 => address) internal cardIdToOwner;
// Owner => number of cards owner owns.
mapping (address => uint256) internal ownerToCardCount;
// Card ID => address approved to transfer on behalf of owner.
mapping (uint256 => address) internal cardIdToApproved;
// Operator => from address to operated or not.
mapping (address => mapping (address => bool)) internal operatorToApprovals;
/* MODIFIERS */
modifier onlyMinter() {
require(msg.sender == minter);
_;
}
/* FUNCTIONS */
/** PRIVATE FUNCTIONS **/
function _addTokenTo(address _to, uint256 _tokenId) internal {
require(cardIdToOwner[_tokenId] == address(0));
ownerToCardCount[_to] = ownerToCardCount[_to] + 1;
cardIdToOwner[_tokenId] = _to;
}
/** PUBLIC FUNCTIONS **/
function setMinter(address _minter) external onlyOwner {
minter = _minter;
}
function mintTemplate(
uint256 _mintLimit,
uint256 _generation,
uint256 _category,
uint256 _variation,
string _name
) external onlyOwner {
require(_mintLimit > 0);
uint256 newTemplateId = templates.push(Template({
generation: _generation,
category: _category,
variation: _variation,
name: _name
})) - 1;
templateIdToMintLimit[newTemplateId] = _mintLimit;
emit TemplateMint(newTemplateId);
}
function mintCard(
uint256 _templateId,
address _owner
) external onlyMinter {
require(templateIdToMintCount[_templateId] < templateIdToMintLimit[_templateId]);
templateIdToMintCount[_templateId] = templateIdToMintCount[_templateId] + 1;
uint256 newCardId = cards.push(_templateId) - 1;
_addTokenTo(_owner, newCardId);
emit Transfer(0, _owner, newCardId);
}
function mintCards(
uint256[] _templateIds,
address _owner
) external onlyMinter {
uint256 mintCount = _templateIds.length;
uint256 templateId;
for (uint256 i = 0; i < mintCount; ++i) {
templateId = _templateIds[i];
require(templateIdToMintCount[templateId] < templateIdToMintLimit[templateId]);
templateIdToMintCount[templateId] = templateIdToMintCount[templateId] + 1;
uint256 newCardId = cards.push(templateId) - 1;
cardIdToOwner[newCardId] = _owner;
emit Transfer(0, _owner, newCardId);
}
// Bulk add to ownerToCardCount.
ownerToCardCount[_owner] = ownerToCardCount[_owner] + mintCount;
}
}
contract CardOwnership is CardMint {
/* FUNCTIONS */
/** PRIVATE FUNCTIONS **/
function _approve(address _owner, address _approved, uint256 _tokenId) internal {
cardIdToApproved[_tokenId] = _approved;
emit Approval(_owner, _approved, _tokenId);
}
function _clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (cardIdToApproved[_tokenId] != address(0)) {
cardIdToApproved[_tokenId] = address(0);
}
}
function _removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownerToCardCount[_from] = ownerToCardCount[_from] - 1;
cardIdToOwner[_tokenId] = address(0);
}
/** PUBLIC FUNCTIONS **/
function approve(address _to, uint256 _tokenId) external {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_approve(owner, _to, _tokenId);
}
function transferFrom(address _from, address _to, uint256 _tokenId) public {
require(isApprovedOrOwner(msg.sender, _tokenId));
require(_from != address(0));
require(_to != address(0));
require(_to != address(this));
_clearApproval(_from, _tokenId);
_removeTokenFrom(_from, _tokenId);
_addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
) public {
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
) public {
transferFrom(_from, _to, _tokenId);
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
) internal returns (bool) {
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == 0x150b7a02);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _operator operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _operator, bool _approved) public {
require(_operator != msg.sender);
require(_operator != address(0));
operatorToApprovals[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return cardIdToApproved[_tokenId];
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
) public view returns (bool) {
return operatorToApprovals[_owner][_operator];
}
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = cardIdToOwner[_tokenId];
require(owner != address(0));
return owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
address owner = cardIdToOwner[_tokenId];
return owner != address(0);
}
}
contract CardAuction is CardOwnership {
ClockAuctionBase public saleAuction;
function setSaleAuction(address _address) external onlyOwner {
ClockAuctionBase candidateContract = ClockAuctionBase(_address);
require(candidateContract.isSaleAuction());
saleAuction = candidateContract;
}
function createSaleAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
) external {
require(saleAuction != address(0));
require(msg.sender == cardIdToOwner[_tokenId]);
_approve(msg.sender, saleAuction, _tokenId);
saleAuction.createAuction(
_tokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
}
contract CardTreasury is CardAuction {
/* FUNCTIONS */
/** PUBLIC FUNCTIONS **/
function getTemplate(uint256 _templateId)
external
view
returns (
uint256 generation,
uint256 category,
uint256 variation,
string name
)
{
require(_templateId < templates.length);
Template storage template = templates[_templateId];
generation = template.generation;
category = template.category;
variation = template.variation;
name = template.name;
}
function getCard(uint256 _cardId)
external
view
returns (
uint256 generation,
uint256 category,
uint256 variation,
string name
)
{
require(_cardId < cards.length);
uint256 templateId = cards[_cardId];
Template storage template = templates[templateId];
generation = template.generation;
category = template.category;
variation = template.variation;
name = template.name;
}
function templateIdOf(uint256 _cardId) external view returns (uint256) {
require(_cardId < cards.length);
return cards[_cardId];
}
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownerToCardCount[_owner];
}
function templateSupply() external view returns (uint256) {
return templates.length;
}
function totalSupply() external view returns (uint256) {
return cards.length;
}
function mintLimitByTemplate(uint256 _templateId) external view returns(uint256) {
require(_templateId < templates.length);
return templateIdToMintLimit[_templateId];
}
function mintCountByTemplate(uint256 _templateId) external view returns(uint256) {
require(_templateId < templates.length);
return templateIdToMintCount[_templateId];
}
function name() external pure returns (string) {
return "Battlebound";
}
function symbol() external pure returns (string) {
return "BB";
}
function tokensOfOwner(address _owner) external view returns (uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 resultIndex = 0;
for (uint256 cardId = 0; cardId < cards.length; ++cardId) {
if (cardIdToOwner[cardId] == _owner) {
result[resultIndex] = cardId;
++resultIndex;
}
}
return result;
}
}
function templatesOfOwner(address _owner) external view returns (uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 resultIndex = 0;
for (uint256 cardId = 0; cardId < cards.length; ++cardId) {
if (cardIdToOwner[cardId] == _owner) {
uint256 templateId = cards[cardId];
result[resultIndex] = templateId;
++resultIndex;
}
}
return result;
}
}
function variationsOfOwner(address _owner) external view returns (uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 resultIndex = 0;
for (uint256 cardId = 0; cardId < cards.length; ++cardId) {
if (cardIdToOwner[cardId] == _owner) {
uint256 templateId = cards[cardId];
Template storage template = templates[templateId];
result[resultIndex] = template.variation;
++resultIndex;
}
}
return result;
}
}
} | STORAGE */ Minter address can mint cards but not templates. | address public minter;
| 6,433,030 | [
1,
19009,
342,
490,
2761,
1758,
848,
312,
474,
18122,
1496,
486,
5539,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
1758,
1071,
1131,
387,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
contract A1 {}
contract B1 is A1 { constructor() public payable {} }
contract A2 { constructor() public {} }
contract B2 is A2 { constructor() public payable {} }
contract B3 { constructor() public payable {} }
contract C {
function f() public payable returns (bool) {
// Make sure none of these revert.
new B1{value: 10}();
new B2{value: 10}();
new B3{value: 10}();
return true;
}
}
// ====
// compileViaYul: also
// ----
// f(), 2000 ether -> true
| Make sure none of these revert. | function f() public payable returns (bool) {
return true;
}
| 12,938,670 | [
1,
6464,
3071,
6555,
434,
4259,
15226,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
284,
1435,
1071,
8843,
429,
1135,
261,
6430,
13,
288,
203,
202,
202,
2463,
638,
31,
203,
202,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// https://eprint.iacr.org/2015/366.pdf
pragma solidity ^0.7.3;
// TODO: checking for quadratic residues has been removed, unclear of implications
library Sloth_Verifiable_Delay {
// verify sloth result y, starting from seed x, over prime p, with t iterations
function verify(
uint256 y,
uint256 x,
uint256 p,
uint256 t
) internal pure returns (bool) {
for (uint256 i; i < t; ++i) {
y = mulmod(y, y, p);
}
x %= p;
if (x == y) return true;
if (p - x == y) return true;
return false;
}
// pow(base, exponent, modulus)
function mod_exp(
uint256 b,
uint256 e,
uint256 m
) internal pure returns (uint256 r) {
r = 1;
for (; e > 0; e >>= 1) {
if (e & 1 == 1) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
}
}
// compute sloth starting from seed x, over prime p, with t iterations
function compute(
uint256 x,
uint256 p,
uint256 t
) internal pure returns (uint256) {
uint256 e = (p + 1) >> 2;
x %= p;
for (uint256 i; i < t; ++i) {
x = mod_exp(x, e, p);
}
return x;
}
}
| verify sloth result y, starting from seed x, over prime p, with t iterations | library Sloth_Verifiable_Delay {
function verify(
uint256 y,
uint256 x,
uint256 p,
uint256 t
) internal pure returns (bool) {
for (uint256 i; i < t; ++i) {
y = mulmod(y, y, p);
}
x %= p;
if (x == y) return true;
if (p - x == y) return true;
return false;
}
) internal pure returns (bool) {
for (uint256 i; i < t; ++i) {
y = mulmod(y, y, p);
}
x %= p;
if (x == y) return true;
if (p - x == y) return true;
return false;
}
function mod_exp(
uint256 b,
uint256 e,
uint256 m
) internal pure returns (uint256 r) {
r = 1;
for (; e > 0; e >>= 1) {
if (e & 1 == 1) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
}
}
function mod_exp(
uint256 b,
uint256 e,
uint256 m
) internal pure returns (uint256 r) {
r = 1;
for (; e > 0; e >>= 1) {
if (e & 1 == 1) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
}
}
function mod_exp(
uint256 b,
uint256 e,
uint256 m
) internal pure returns (uint256 r) {
r = 1;
for (; e > 0; e >>= 1) {
if (e & 1 == 1) {
r = mulmod(r, b, m);
}
b = mulmod(b, b, m);
}
}
function compute(
uint256 x,
uint256 p,
uint256 t
) internal pure returns (uint256) {
uint256 e = (p + 1) >> 2;
x %= p;
for (uint256 i; i < t; ++i) {
x = mod_exp(x, e, p);
}
return x;
}
function compute(
uint256 x,
uint256 p,
uint256 t
) internal pure returns (uint256) {
uint256 e = (p + 1) >> 2;
x %= p;
for (uint256 i; i < t; ++i) {
x = mod_exp(x, e, p);
}
return x;
}
}
| 12,943,906 | [
1,
8705,
4694,
76,
563,
677,
16,
5023,
628,
5009,
619,
16,
1879,
17014,
293,
16,
598,
268,
11316,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
12083,
9708,
10370,
67,
3945,
8424,
67,
6763,
288,
203,
225,
445,
3929,
12,
203,
565,
2254,
5034,
677,
16,
203,
565,
2254,
5034,
619,
16,
203,
565,
2254,
5034,
293,
16,
203,
565,
2254,
5034,
268,
203,
203,
203,
225,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
268,
31,
965,
77,
13,
288,
203,
1377,
677,
273,
14064,
1711,
12,
93,
16,
677,
16,
293,
1769,
203,
565,
289,
203,
203,
565,
619,
30582,
293,
31,
203,
203,
565,
309,
261,
92,
422,
677,
13,
327,
638,
31,
203,
203,
565,
309,
261,
84,
300,
619,
422,
677,
13,
327,
638,
31,
203,
203,
565,
327,
629,
31,
203,
225,
289,
203,
203,
225,
262,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
565,
364,
261,
11890,
5034,
277,
31,
277,
411,
268,
31,
965,
77,
13,
288,
203,
1377,
677,
273,
14064,
1711,
12,
93,
16,
677,
16,
293,
1769,
203,
565,
289,
203,
203,
565,
619,
30582,
293,
31,
203,
203,
565,
309,
261,
92,
422,
677,
13,
327,
638,
31,
203,
203,
565,
309,
261,
84,
300,
619,
422,
677,
13,
327,
638,
31,
203,
203,
565,
327,
629,
31,
203,
225,
289,
203,
203,
225,
445,
681,
67,
2749,
12,
203,
565,
2254,
5034,
324,
16,
203,
565,
2254,
5034,
425,
16,
203,
565,
2254,
5034,
312,
203,
225,
262,
2713,
16618,
1135,
261,
11890,
5034,
436,
13,
288,
203,
565,
436,
273,
404,
31,
203,
203,
565,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IBurnable.sol";
import "./interfaces/IFarmManager.sol";
// Farm distributes the ERC20 rewards based on staked LP to each user.
contract Farm {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 lastClaimTime;
uint256 withdrawTime;
// We do some fancy math here. Basically, any point in time, the amount of ERC20s
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accERC20PerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accERC20PerShare` (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 stakingToken; // Address of staking token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. ERC20s to distribute per block.
uint256 lastRewardBlock; // Last block number that ERC20s distribution occurs.
uint256 accERC20PerShare; // Accumulated ERC20s per share, times 1e36.
uint256 supply; // changes with unstakes.
bool isLP; // if the staking token is an LP token.
bool isBurnable; // if the staking token is burnable
}
// Address of the ERC20 Token contract.
IERC20 public erc20;
// The total amount of ERC20 that's paid out as reward.
uint256 public paidOut;
// ERC20 tokens rewarded per block.
uint256 public rewardPerBlock;
// Manager interface to get globals for all farms.
IFarmManager public manager;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// The block number when farming starts.
uint256 public startBlock;
// Seconds per epoch (1 day)
uint256 public constant SECS_EPOCH = 86400;
// events
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid);
event Claim(address indexed user, uint256 indexed pid);
event Unstake(address indexed user, uint256 indexed pid);
event Initialize(IERC20 erc20, uint256 rewardPerBlock, uint256 startBlock, address manager);
constructor(IERC20 _erc20, uint256 _rewardPerBlock, uint256 _startBlock, address _manager) public {
erc20 = _erc20;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
manager = IFarmManager(_manager);
emit Initialize(_erc20, _rewardPerBlock, _startBlock, _manager);
}
// Fund the farm, increase the end block.
function fund(address _funder, uint256 _amount) external {
require(msg.sender == address(manager), "fund: sender is not manager");
erc20.safeTransferFrom(_funder, address(this), _amount);
}
// Update the given pool's ERC20 allocation point. Can only be called by the manager.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external {
require(msg.sender == address(manager), "set: sender is not manager");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Add a new staking token to the pool. Can only be called by the manager.
function add(uint256 _allocPoint, IERC20 _stakingToken, bool _isLP, bool _isBurnable, bool _withUpdate) external {
require(msg.sender == address(manager), "fund: sender is not manager");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
stakingToken: _stakingToken,
supply: 0,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accERC20PerShare: 0,
isLP: _isLP,
isBurnable: _isBurnable
}));
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
uint256 lastBlock = block.number;
if (lastBlock <= pool.lastRewardBlock) {
return;
}
if (pool.supply == 0) {
pool.lastRewardBlock = lastBlock;
return;
}
uint256 nrOfBlocks = lastBlock.sub(pool.lastRewardBlock);
uint256 erc20Reward = nrOfBlocks.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
pool.accERC20PerShare = pool.accERC20PerShare.add(erc20Reward.mul(1e36).div(pool.supply));
pool.lastRewardBlock = block.number;
}
// move LP tokens from one farm to another. only callable by Manager.
function move(uint256 _pid, address _mover) external {
require(msg.sender == address(manager), "move: sender is not manager");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_mover];
updatePool(_pid);
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(_mover, pendingAmount);
pool.supply = pool.supply.sub(user.amount);
pool.stakingToken.safeTransfer(address(manager), user.amount);
user.amount = 0;
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
emit Withdraw(msg.sender, _pid);
}
// Deposit LP tokens to Farm for ERC20 allocation.
// can come from manager or user address directly.
// In the case the call is coming from the manager, msg.sender is the manager.
function deposit(uint256 _pid, address _depositor, uint256 _amount) external {
require(manager.getPaused()==false, "deposit: farm paused");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_depositor];
require(user.withdrawTime == 0, "deposit: user is unstaking");
// If we're not called by the farm manager, then we must ensure that the caller is the depositor.
// This way we avoid the case where someone else commits the deposit, after the depositor
// granted allowance to the farm.
if(msg.sender != address(manager)) {
require(msg.sender == _depositor, "deposit: the caller must be the depositor");
}
updatePool(_pid);
if (user.amount > 0) {
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(_depositor, pendingAmount);
}
// We tranfer from the msg.sender, because in the case when we're called by the farm manager (change pool scenario)
// it's the FM who owns the tokens, not the depositor (who in this case is the user who changes pools).
pool.stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
pool.supply = pool.supply.add(_amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
emit Deposit(_depositor, _pid, _amount);
}
// Distribute rewards and start unstake period.
function withdraw(uint256 _pid) external {
require(manager.getPaused()==false, "withdraw: farm paused");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "withdraw: amount must be greater than 0");
require(user.withdrawTime == 0, "withdraw: user is unstaking");
updatePool(_pid);
// transfer any rewards due
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(msg.sender, pendingAmount);
pool.supply = pool.supply.sub(user.amount);
user.rewardDebt = 0;
user.withdrawTime = block.timestamp;
emit Withdraw(msg.sender, _pid);
}
// unstake LP tokens from Farm. if done within "unstakeEpochs" days, apply burn.
function unstake(uint256 _pid) external {
require(manager.getPaused()==false, "unstake: farm paused");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.withdrawTime > 0, "unstake: user is not unstaking");
updatePool(_pid);
//apply burn fee if unstaking before unstake epochs.
uint256 unstakeEpochs = manager.getUnstakeEpochs();
uint256 burnRate = manager.getBurnRate();
address redistributor = manager.getRedistributor();
if((user.withdrawTime.add(SECS_EPOCH.mul(unstakeEpochs)) > block.timestamp) && burnRate > 0){
uint penalty = user.amount.mul(burnRate).div(1000);
user.amount = user.amount.sub(penalty);
// if the staking address is an LP, send 50% of penalty to redistributor, and 50% to lp lock address.
if(pool.isLP){
uint256 redistributorPenalty = penalty.div(2);
pool.stakingToken.safeTransfer(redistributor, redistributorPenalty);
pool.stakingToken.safeTransfer(manager.getLpLock(), penalty.sub(redistributorPenalty));
}else {
// for normal ERC20 tokens, a portion (50% by default) of the penalty is sent to the redistributor address
uint256 burnRatio = manager.getBurnRatio();
uint256 burnAmount = penalty.mul(burnRatio).div(1000);
pool.stakingToken.safeTransfer(redistributor, penalty.sub(burnAmount));
if(pool.isBurnable){
//if the staking token is burnable, the second portion (50% by default) is burned
IBurnable(address(pool.stakingToken)).burn(burnAmount);
}else{
//if the staking token is not burnable, the second portion (50% by default) is sent to burn valley
pool.stakingToken.safeTransfer(manager.getBurnValley(), burnAmount);
}
}
}
uint userAmount = user.amount;
// allows user to stake again.
user.withdrawTime = 0;
user.amount = 0;
pool.stakingToken.safeTransfer(address(msg.sender), userAmount);
emit Unstake(msg.sender, _pid);
}
// claim LP tokens from Farm.
function claim(uint256 _pid) external {
require(manager.getPaused() == false, "claim: farm paused");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "claim: amount is equal to 0");
require(user.withdrawTime == 0, "claim: user is unstaking");
updatePool(_pid);
uint256 pendingAmount = user.amount.mul(pool.accERC20PerShare).div(1e36).sub(user.rewardDebt);
erc20Transfer(msg.sender, pendingAmount);
user.rewardDebt = user.amount.mul(pool.accERC20PerShare).div(1e36);
user.lastClaimTime = block.timestamp;
emit Claim(msg.sender, _pid);
}
// Transfer ERC20 and update the required ERC20 to payout all rewards
function erc20Transfer(address _to, uint256 _amount) internal {
erc20.transfer(_to, _amount);
paidOut += _amount;
}
// emergency withdraw rewards. only owner. EMERGENCY ONLY.
function emergencyWithdrawRewards(address _receiver) external {
require(msg.sender == address(manager), "emergencyWithdrawRewards: sender is not manager");
uint balance = erc20.balanceOf(address(this));
erc20.safeTransfer(_receiver, balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity 0.7.6;
interface IBurnable {
function burn(uint256 amount) external;
function balanceOf(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
interface IFarmManager {
function getPaused() external view returns(bool);
function getBurnRate() external view returns(uint256);
function getBurnRatio() external view returns(uint256);
function getUnstakeEpochs() external view returns(uint256);
function getRedistributor() external view returns(address);
function getLpLock() external view returns(address);
function getBurnValley() external view returns(address);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | Fund the farm, increase the end block. | function fund(address _funder, uint256 _amount) external {
require(msg.sender == address(manager), "fund: sender is not manager");
erc20.safeTransferFrom(_funder, address(this), _amount);
}
| 1,494,669 | [
1,
42,
1074,
326,
284,
4610,
16,
10929,
326,
679,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
284,
1074,
12,
2867,
389,
74,
9341,
16,
2254,
5034,
389,
8949,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1758,
12,
4181,
3631,
315,
74,
1074,
30,
5793,
353,
486,
3301,
8863,
203,
3639,
6445,
71,
3462,
18,
4626,
5912,
1265,
24899,
74,
9341,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.11;
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
pragma solidity ^0.4.0;//please import oraclizeAPI_pre0.4.sol when solidity < 0.4.0
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id);
function getPrice(string _datasource) returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice);
function useCoupon(string _coupon);
function setProofType(byte _proofType);
function setConfig(bytes32 _config);
function setCustomGasPrice(uint _gasPrice);
function randomDS_getSessionPubKeyHash() returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() 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());
oraclize.useCoupon(code);
_;
}
function oraclize_setNetwork(uint8 networkID) 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) {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) {
}
function oraclize_useCoupon(string code) oraclizeAPI internal {
oraclize.useCoupon(code);
}
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_setConfig(bytes32 config) oraclizeAPI internal {
return oraclize.setConfig(config);
}
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 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 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 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 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 returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal 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 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 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 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 returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
if ((_nbytes == 0)||(_nbytes > 32)) throw;
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, sha3(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(sha3(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(sha3(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] = 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)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) throw;
_;
}
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 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 (!(sha3(keyhash) == sha3(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, sha3(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] == sha3(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 returns (bytes) {
uint minLength = length + toOffset;
if (to.length < minLength) {
// Buffer too small
throw; // 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>
contract YankeesOrioles48 is usingOraclize {
/* Declaration */
address public OWNERS = 0xC3eD2d481B9d75835EC04174b019A7eAF2Faf78A;
uint public constant COMMISSION = 0; // Commission for the owner
uint public constant MIN_BET = 0.01 ether;
uint public EXPECTED_START = 1523207100; // When the bet's event is expected to start
uint public EXPECTED_END = 1523237146; // When the bet's event is expected to end
uint public constant BETTING_OPENS = 1523132564;
uint public BETTING_CLOSES = EXPECTED_START - 60; // Betting closes a minute before the bet event starts
uint public constant PING_ORACLE_INTERVAL = 60 * 60 * 24; // Ping oracle every 24 hours until completion (or cancelation)
uint public ORACLIZE_GAS = 200000;
uint public CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24; // Cancelation date is 24 hours after the expected end
uint public RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30; // Any leftover money is returned to owners 1 month after bet ends
bool public completed;
bool public canceled;
bool public ownersPayed;
uint public ownerPayout;
bool public returnedToOwners;
uint public winnerDeterminedDate;
uint public numCollected = 0;
bytes32 public nextScheduledQuery;
uint public oraclizeFees;
uint public collectionFees;
struct Better {
uint betAmount;
uint betOption;
bool withdrawn;
}
mapping(address => Better) betterInfo;
address[] public betters;
uint[2] public totalAmountsBet;
uint[2] public numberOfBets;
uint public totalBetAmount;
uint public winningOption = 2;
/* Events */
event BetMade();
/* Modifiers */
// Modifier to only allow the
// determination of the winner
modifier canDetermineWinner() {
require (winningOption == 2 && !completed && !canceled && now > BETTING_CLOSES && now >= EXPECTED_END);
_;
}
// Modifier to only allow emptying
// the remaining value of the contract
// to owners.
modifier canEmptyRemainings() {
require(canceled || completed);
uint numRequiredToCollect = canceled ? (numberOfBets[0] + numberOfBets[1]) : numberOfBets[winningOption];
require ((now >= RETURN_DATE && !canceled) || (numCollected == numRequiredToCollect));
_;
}
// Modifier to only allow the collection
// of bet payouts when winner is determined,
// (or withdrawals if the bet is canceled)
modifier collectionsEnabled() {
require (canceled || (winningOption != 2 && completed && now > BETTING_CLOSES));
_;
}
// Modifier to only allow the execution of
// owner payout when winner is determined
modifier canPayOwners() {
require (!canceled && winningOption != 2 && completed && !ownersPayed && now > BETTING_CLOSES);
_;
}
// Modifier to only allow the execution of
// certain functions when betting is closed
modifier bettingIsClosed() {
require (now >= BETTING_CLOSES);
_;
}
// Modifier to only allow the execution of
// certain functions restricted to the owners
modifier onlyOwnerLevel() {
require(
OWNERS == msg.sender
);
_;
}
/* Functions */
// Constructor
function YankeesOrioles48() public payable {
oraclize_setCustomGasPrice(1000000000);
callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for outcome
}
function changeGasLimitAndPrice(uint gas, uint price) public onlyOwnerLevel {
ORACLIZE_GAS = gas;
oraclize_setCustomGasPrice(price);
}
// Change bet expected times
function setExpectedTimes(uint _EXPECTED_START, uint _EXPECTED_END) public onlyOwnerLevel {
setExpectedStart(_EXPECTED_START);
setExpectedEnd(_EXPECTED_END);
}
// Change bet expected start time
function setExpectedStart(uint _EXPECTED_START) public onlyOwnerLevel {
EXPECTED_START = _EXPECTED_START;
BETTING_CLOSES = EXPECTED_START - 60;
}
// Change bet expected end time
function setExpectedEnd(uint _EXPECTED_END) payable public onlyOwnerLevel {
require(_EXPECTED_END > EXPECTED_START);
EXPECTED_END = _EXPECTED_END;
CANCELATION_DATE = EXPECTED_END + 60 * 60 * 24;
RETURN_DATE = EXPECTED_END + 60 * 60 * 24 * 30;
callOracle(EXPECTED_END, ORACLIZE_GAS); // Kickoff Oracle checking for winner
}
function callOracle(uint timeOrDelay, uint gas) private {
require(canceled != true && completed != true);
// Make a call to the oracle —
// usually a script hosted on IPFS that
// Oraclize deploys, after a given delay. We
// leave nested query as default to maximize
// optionality for queries.
// To readers of the code (aka prospective betters)
// if this is a computation query, you can view the
// script we use to compute the winner, as it is hosted
// on IPFS. The first argument in the computation query
// is the IPFS hash (script would be located at
// ipfs.io/ipfs/<HASH>). The file hosted at this hash
// is actually a zipped folder that contains a Dockerfile and
// the script. So, if you download the file at the hash provided,
// ensure to convert it to a .zip, unzip it, and read the code.
// Oraclize uses the Dockerfile to deploy this script.
// Look over the Oraclize documentation to verify this
// for yourself.
nextScheduledQuery = makeOraclizeQuery(timeOrDelay, "nested", "[computation] ['QmUSbN6LdTkyMp3NiCYikRgiUKubroB4rsgk89FpWTsqih', '7bdfb762-7b53-4da1-9508-fce27313a90f', '${[decrypt] BDqaImWUPbuh4CfLxWlm9AeL81COzTfOcRdXBE1KcViZhCiSAGajs6vR63scOBh6UZdq7rXtG3niT4u2yFnyMyiZGc6hOGRlouiN5hqyh5dS9QkrVccgYlCn9qvvvw8eMurmRL3mbdTG}']", gas);
}
function makeOraclizeQuery(uint timeOrDelay, string datasource, string query, uint gas) private returns(bytes32) {
oraclizeFees += oraclize_getPrice(datasource, gas);
return oraclize_query(timeOrDelay, datasource, query, gas);
}
// Determine the outcome manually,
// immediately
function determineWinner(uint gas, uint gasPrice) payable public onlyOwnerLevel canDetermineWinner {
ORACLIZE_GAS = gas;
oraclize_setCustomGasPrice(gasPrice);
callOracle(0, ORACLIZE_GAS);
}
// Callback from Oraclize
function __callback(bytes32 queryId, string result, bytes proof) public canDetermineWinner {
require(msg.sender == oraclize_cbAddress());
// The Oracle must always return
// an integer (either 0 or 1, or if not then)
// it should be 2
if (keccak256(result) != keccak256("0") && keccak256(result) != keccak256("1")) {
// Reschedule winner determination,
// unless we're past the point of
// cancelation. If nextScheduledQuery is
// not the current query, it means that
// there's a scheduled future query, so
// we can wait for that instead of scheduling
// another one now (otherwise this would cause
// dupe queries).
if (now >= CANCELATION_DATE) {
cancel();
}
else if (nextScheduledQuery == queryId) {
callOracle(PING_ORACLE_INTERVAL, ORACLIZE_GAS);
}
}
else {
setWinner(parseInt(result));
}
}
function setWinner(uint winner) private {
completed = true;
canceled = false;
winningOption = winner;
winnerDeterminedDate = now;
payOwners();
}
// Returns the total amounts betted
// for the sender
function getUserBet(address addr) public constant returns(uint[]) {
uint[] memory bets = new uint[](2);
bets[betterInfo[addr].betOption] = betterInfo[addr].betAmount;
return bets;
}
// Returns whether a user has withdrawn
// money or not.
function userHasWithdrawn(address addr) public constant returns(bool) {
return betterInfo[addr].withdrawn;
}
// Returns whether winning collections are
// now available, or not.
function collectionsAvailable() public constant returns(bool) {
return (completed && winningOption != 2 && now >= (winnerDeterminedDate + 600)); // At least 10 mins has to pass between determining winner and enabling payout, so that we have time to revert the bet in case we detect suspicious betting activty (eg. a hacker bets a lot to steal the entire losing pot, and hacks the oracle)
}
// Returns true if we can bet (in betting window)
function canBet() public constant returns(bool) {
return (now >= BETTING_OPENS && now < BETTING_CLOSES && !canceled && !completed);
}
// Function for user to bet on launch
// outcome
function bet(uint option) public payable {
require(canBet() == true);
require(msg.value >= MIN_BET);
require(betterInfo[msg.sender].betAmount == 0 || betterInfo[msg.sender].betOption == option);
// Add better to better list if they
// aren't already in it
if (betterInfo[msg.sender].betAmount == 0) {
betterInfo[msg.sender].betOption = option;
numberOfBets[option]++;
betters.push(msg.sender);
}
// Perform bet
betterInfo[msg.sender].betAmount += msg.value;
totalBetAmount += msg.value;
totalAmountsBet[option] += msg.value;
BetMade(); // Trigger event
}
// Empty remainder of the value in the
// contract to the owners.
function emptyRemainingsToOwners() private canEmptyRemainings {
OWNERS.transfer(this.balance);
returnedToOwners = true;
}
function returnToOwners() public onlyOwnerLevel canEmptyRemainings {
emptyRemainingsToOwners();
}
// Performs payout to owners
function payOwners() private canPayOwners {
if (COMMISSION == 0) {
ownersPayed = true;
ownerPayout = 0;
if (numberOfBets[winningOption] > 0) {
collectionFees = ((oraclizeFees != 0) ? (oraclizeFees / numberOfBets[winningOption] + 1) : 0); // We add 1 wei to act as a ceil for the integer div -- important because the contract cannot afford to lose that spare change, as it will gaurantee that the final payout collection will fail.
}
return;
}
// Calculate total pool of ETH
// betted for the two outcomes.
uint losingChunk = totalAmountsBet[1 - winningOption];
ownerPayout = (losingChunk - oraclizeFees) / COMMISSION; // Payout to the owner; commission of losing pot, minus the same % of the fees
if (numberOfBets[winningOption] > 0) {
collectionFees = ((oraclizeFees != 0) ? ((oraclizeFees - oraclizeFees / COMMISSION) / numberOfBets[winningOption] + 1) : 0); // The fees to be distributed to the collectors, after owner payout. See reasoning above for adding the 1 wei.
}
// Equal weight payout to the owners
OWNERS.transfer(ownerPayout);
ownersPayed = true;
}
function cancelBet() payable public onlyOwnerLevel {
cancel();
}
// Cancel bet and relase all the bets back to
// the betters if, for any reason, payouts cannot be
// completed. (For example Oracle fails.) Triggered by owners.
function cancel() private {
canceled = true;
completed = false;
}
// Fallback function in case someone sends
// ether to the contract so it doesn't get
// lost. Could be used by us owners as buffer
// value in case payouts fail.
function() payable public {
}
// Function that lets betters collect their
// money, either if the bet was canceled,
// or if they won.
function collect() public collectionsEnabled {
address better = msg.sender;
require(betterInfo[better].betAmount > 0);
require(!betterInfo[better].withdrawn);
require(canceled != completed);
require(canceled || (completed && betterInfo[better].betOption == winningOption));
require(now >= (winnerDeterminedDate + 600));
uint payout = 0;
if (!canceled) {
// On top of their original bet,
// add in profit, which is a weighted
// proportion of the losing pot, relative
// to their contribution to the winning pot,
// minus owner commission.
uint losingChunk = totalAmountsBet[1 - winningOption];
payout = betterInfo[better].betAmount + (betterInfo[better].betAmount * (losingChunk - ownerPayout) / totalAmountsBet[winningOption]) - collectionFees;
}
else {
payout = betterInfo[better].betAmount;
}
if (payout > 0) {
better.transfer(payout);
betterInfo[better].withdrawn = true;
numCollected++;
}
}
} | The fees to be distributed to the collectors, after owner payout. See reasoning above for adding the 1 wei.
| collectionFees = ((oraclizeFees != 0) ? ((oraclizeFees - oraclizeFees / COMMISSION) / numberOfBets[winningOption] + 1) : 0); | 443,271 | [
1,
1986,
1656,
281,
358,
506,
16859,
358,
326,
3274,
1383,
16,
1839,
3410,
293,
2012,
18,
2164,
3971,
310,
5721,
364,
6534,
326,
404,
732,
77,
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
] | [
1,
1,
1,
1,
1,
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,
3639,
1849,
2954,
281,
273,
14015,
280,
10150,
554,
2954,
281,
480,
374,
13,
692,
14015,
280,
10150,
554,
2954,
281,
300,
578,
10150,
554,
2954,
281,
342,
5423,
15566,
13,
342,
7922,
38,
2413,
63,
8082,
2093,
1895,
65,
397,
404,
13,
294,
374,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 MerkleProofUpgradeable {
/**
* @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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// 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.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.9;
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
/// @title CollabSplitterFactory
/// @author Simon Fremaux (@dievardump)
contract CollabSplitter is Initializable {
event ETHClaimed(address operator, address account, uint256 amount);
event ERC20Claimed(
address operator,
address account,
uint256 amount,
address token
);
struct ERC20Data {
uint256 totalReceived;
uint256 lastBalance;
}
// string public name;
bytes32 public merkleRoot;
// keeps track of how much was received in ETH since the start
uint256 public totalReceived;
// keeps track of how much an account already claimed ETH
mapping(address => uint256) public alreadyClaimed;
// keeps track of ERC20 data
mapping(address => ERC20Data) public erc20Data;
// keeps track of how much an account already claimed for a given ERC20
mapping(address => mapping(address => uint256)) private erc20AlreadyClaimed;
function initialize(bytes32 merkleRoot_) external initializer {
merkleRoot = merkleRoot_;
}
receive() external payable {
totalReceived += msg.value;
}
/// @notice Does claimETH and claimERC20 in one call
/// @param account the account we want to claim for
/// @param percent the allocation for this account | 2 decimal basis, meaning 1 = 100, 2.5 = 250 etc...
/// @param merkleProof the merkle proof used to ensure this claim is legit
/// @param erc20s the ERC20 contracts addresses to claim from
function claimBatch(
address account,
uint256 percent,
bytes32[] memory merkleProof,
address[] memory erc20s
) public {
require(
MerkleProofUpgradeable.verify(
merkleProof,
merkleRoot,
getNode(account, percent)
),
'Invalid proof.'
);
_claimETH(account, percent);
for (uint256 i; i < erc20s.length; i++) {
_claimERC20(account, percent, erc20s[i]);
}
}
/// @notice Allows to claim the ETH for an account
/// @param account the account we want to claim for
/// @param percent the allocation for this account | 2 decimal basis, meaning 1 = 100, 2.5 = 250 etc...
/// @param merkleProof the merkle proof used to ensure this claim is legit
function claimETH(
address account,
uint256 percent,
bytes32[] memory merkleProof
) public {
require(
MerkleProofUpgradeable.verify(
merkleProof,
merkleRoot,
getNode(account, percent)
),
'Invalid proof.'
);
_claimETH(account, percent);
}
/// @notice Allows to claim an ERC20 for an account
/// @dev To be able to do so, every time a claim is asked, we will compare both current and last known
/// balance for this contract, allowing to keep up to date on how much it has ever received
/// then we can calculate the full amount due to the account, and substract the amount already claimed
/// @param account the account we want to claim for
/// @param percent the allocation for this account | 2 decimal basis, meaning 1% = 100, 2.5% = 250 etc...
/// @param merkleProof the merkle proof used to ensure this claim is legit
/// @param erc20s the ERC20 contracts addresses to claim from
function claimERC20(
address account,
uint256 percent,
bytes32[] memory merkleProof,
address[] memory erc20s
) public {
require(
MerkleProofUpgradeable.verify(
merkleProof,
merkleRoot,
getNode(account, percent)
),
'Invalid proof.'
);
for (uint256 i; i < erc20s.length; i++) {
_claimERC20(account, percent, erc20s[i]);
}
}
/// @notice Function to create the "node" in the merkle tree, given account and allocation
/// @param account the account
/// @param percent the allocation
/// @return the bytes32 representing the node / leaf
function getNode(address account, uint256 percent)
public
pure
returns (bytes32)
{
return keccak256(abi.encode(account, percent));
}
/// @notice Helper allowing to know how much ETH is still claimable for a list of accounts
/// @param accounts the account to check for
/// @param percents the allocation for this account
function getBatchClaimableETH(
address[] memory accounts,
uint256[] memory percents
) public view returns (uint256[] memory) {
uint256[] memory claimable = new uint256[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
claimable[i] = _calculateDue(
totalReceived,
percents[i],
alreadyClaimed[accounts[i]]
);
}
return claimable;
}
/// @notice Helper allowing to know how much of an ERC20 is still claimable for a list of accounts
/// @param accounts the account to check for
/// @param percents the allocation for this account
/// @param token the token (ERC20 contract) to check on
function getBatchClaimableERC20(
address[] memory accounts,
uint256[] memory percents,
address token
) public view returns (uint256[] memory) {
ERC20Data memory data = erc20Data[token];
uint256 balance = IERC20(token).balanceOf(address(this));
uint256 sinceLast = balance - data.lastBalance;
// the difference between last claim and today's balance is what has been received as royalties
// so we can add it to the total received
data.totalReceived += sinceLast;
uint256[] memory claimable = new uint256[](accounts.length);
for (uint256 i; i < accounts.length; i++) {
claimable[i] = _calculateDue(
data.totalReceived,
percents[i],
erc20AlreadyClaimed[accounts[i]][token]
);
}
return claimable;
}
/// @notice Helper to query how much an account already claimed for a list of tokens
/// @param account the account to check for
/// @param tokens the tokens addresses
/// use address(0) to query for nativ chain token
function getBatchClaimed(address account, address[] memory tokens)
public
view
returns (uint256[] memory)
{
uint256[] memory claimed = new uint256[](tokens.length);
for (uint256 i; i < tokens.length; i++) {
if (tokens[i] == address(0)) {
claimed[i] = alreadyClaimed[account];
} else {
claimed[i] = erc20AlreadyClaimed[account][tokens[i]];
}
}
return claimed;
}
/// @dev internal function to claim ETH
/// @param account the account we want to claim for
/// @param percent the allocation for this account | 2 decimal basis, meaning 1% = 100, 2.5% = 250 etc...
function _claimETH(address account, uint256 percent) internal {
if (totalReceived == 0) return;
uint256 dueNow = _calculateDue(
totalReceived,
percent,
alreadyClaimed[account]
);
if (dueNow == 0) return;
// update the already claimed first, blocking reEntrancy
alreadyClaimed[account] += dueNow;
// send the due;
// @TODO: .call{}() calls with all gas left in the tx
// Question: Should we limit the gas used here?!
// It has to be at least enough for contracts (Gnosis etc...) to proxy and store
(bool success, ) = account.call{value: dueNow}('');
require(success, 'Error when sending ETH');
emit ETHClaimed(msg.sender, account, dueNow);
}
/// @dev internal function to claim an ERC20
/// @param account the account we want to claim for
/// @param percent the allocation for this account | 2 decimal basis, meaning 1% = 100, 2.5% = 250 etc...
/// @param erc20 the ERC20 contract to claim from
function _claimERC20(
address account,
uint256 percent,
address erc20
) internal {
ERC20Data storage data = erc20Data[erc20];
uint256 balance = IERC20(erc20).balanceOf(address(this));
uint256 sinceLast = balance - data.lastBalance;
// the difference between last known balance and today's balance is what has been received as royalties
// so we can add it to the total received
data.totalReceived += sinceLast;
// now we can calculate how much is due to current account the same way we do for ETH
if (data.totalReceived == 0) return;
uint256 dueNow = _calculateDue(
data.totalReceived,
percent,
erc20AlreadyClaimed[account][erc20]
);
if (dueNow == 0) return;
// update the already claimed first
erc20AlreadyClaimed[account][erc20] += dueNow;
// transfer the dueNow
require(
IERC20(erc20).transfer(account, dueNow),
'Error when sending ERC20'
);
// update the lastBalance, so we can recalculate next time
// we could save this call by doing (balance - dueNow) but some ERC20 might have weird behavior
// and actually make the balance different than this after the transfer
// so for safety, reading the actual state again
data.lastBalance = IERC20(erc20).balanceOf(address(this));
// emitting an event will allow to identify claimable ERC20 in TheGraph
// to be able to display them in the UI and keep stats
emit ERC20Claimed(msg.sender, account, dueNow, erc20);
}
/// @dev Helpers that calculates how much is still left to claim
/// @param total total received
/// @param percent allocation
/// @param claimed what was already claimed
/// @return what is left to claim
function _calculateDue(
uint256 total,
uint256 percent,
uint256 claimed
) internal pure returns (uint256) {
return (total * percent) / 10000 - claimed;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import './CollabSplitterFactory/CollabSplitterFactoryStorage.sol';
import './CollabSplitter.sol';
/// @title CollabSplitterFactory
/// @author Simon Fremaux (@dievardump)
/// @notice This contract allows people to create a "Splitter" -> a contract that will
/// allow to split the ETH or ERC20 it received, between several addresses
/// This contract is upgradeable, because we might have to add functionalities
/// or versioning over time.
/// However, the Factory has no authority over a Splitter after it's created
/// which ensure that updates to the current contract
/// won't create any problems / exploits on existing Splitter
contract CollabSplitterFactory is
OwnableUpgradeable,
CollabSplitterFactoryStorage
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// emitted when a splitter contract is created
event SplitterCreated(
address indexed splitter,
string name,
address[] recipients,
uint256[] amounts
);
constructor() {}
function initialize(address splitterImplementation, address owner_)
external
initializer
{
_setSplitterImplementation(splitterImplementation);
if (owner_ != address(0)) {
transferOwnership(owner_);
}
}
/// @notice Getter for the Splitter Implementation
function getSplitterImplementation() public view returns (address) {
return _splitterImplementation;
}
/// @notice Creates a new CollabSplitter contract
/// @dev the contract created is a minimal proxy to the _splitterImplementation
/// the list of recipients (and the corresponding amounts) should then be used in the exact same order
/// to create the merkleProof and merkleRoot
/// @param name_ name of the Splitter (for convenience)
/// @param merkleRoot merkle root of the tree of recipients
/// @param recipients list of recipients
/// @param amounts list of amounts
/// @return newContract the address of the new contract
function createSplitter(
string memory name_,
bytes32 merkleRoot,
address[] memory recipients,
uint256[] memory amounts
) external payable returns (address newContract) {
require(_splitterImplementation != address(0), '!NO_IMPLEMENTATION!');
require(recipients.length == amounts.length, '!LENGTH_MISMATCH!');
uint256 total;
for (uint256 i; i < amounts.length; i++) {
require(amounts[i] != 0, '!NO_NULL_VALUE!');
total += amounts[i];
}
require(total == 10000, '!VALUE_MUST_BE_100!');
// create minimal proxy to _splitterImplementation
newContract = ClonesUpgradeable.clone(_splitterImplementation);
// initialize the non upgradeable proxy
CollabSplitter(payable(newContract)).initialize(merkleRoot);
// emit an event with all the data needed to reconstruct later the merkle tree
// and allow people to claim their eth / tokens
// using events will allow to store everything in TheGraph (or similar) in a decentralized way
// while still be less expensive than storing in the CollabSplitter storage
emit SplitterCreated(newContract, name_, recipients, amounts);
}
/// @notice Setter for the Splitter Implementation
/// @param implementation the address to proxy calls to
function setSplitterImplementation(address implementation)
public
onlyOwner
{
_setSplitterImplementation(implementation);
}
/// @dev internal setter for the Splitter Implementation
/// @param implementation the address to proxy calls to
function _setSplitterImplementation(address implementation) internal {
_splitterImplementation = implementation;
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import '@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol';
/// @title CollabSplitterFactoryStorage
/// @author Simon Fremaux (@dievardump)
contract CollabSplitterFactoryStorage {
// current Splitter implementation
address internal _splitterImplementation;
// gap
uint256[50] private __gap;
} | @notice Getter for the Splitter Implementation | function getSplitterImplementation() public view returns (address) {
return _splitterImplementation;
}
| 14,332,900 | [
1,
8461,
364,
326,
5385,
387,
25379,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1322,
1127,
387,
13621,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
4939,
387,
13621,
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
] |
pragma solidity ^0.4.23;
import "openzeppelin-solidity/contracts/token/ERC721/ERC721Receiver.sol";
import "contracts/Goods.sol";
/**
* @title Trade contract that allows atomic exchange of multiple goods
* @dev Only two trading parties are supported
*/
contract Trade is ERC721Receiver {
event GoodAdded(address indexed _trader, uint256 _goodID);
event GoodRemoved(address indexed _trader, uint256 _goodID);
event GoodExchanged(
address indexed _from,
address indexed _to,
uint256 indexed _goodID
);
event TradeAccepted(address indexed _trader);
event TradeCancelled(address indexed _trader);
event TradeFinalized();
event GoodsPulled(address indexed _trader);
address[2] public traders;
mapping(address => bool) public traderAccepted;
mapping(address => bool) public traderPulledGoods;
Goods goods;
bool public isActive = true;
mapping(uint256 => address) public goodsTrader;
constructor(Goods _goods, address[2] _traders) public {
goods = _goods;
traders = _traders;
}
modifier noneAccepted() {
require(_numTradersAccepted() == 0);
_;
}
modifier activeOnly() {
require(isActive);
_;
}
modifier traderOnly() {
require(isTrader(msg.sender));
_;
}
/**
* @dev Return the total numbers of traders
* @return Number of traders
*/
function numTraders() external view returns (uint256) {
return traders.length;
}
/**
* @dev Return the number of traders that have accepted this trade
* @return Number of traders that accepted
*/
function numTradersAccepted() external view returns (uint256) {
return _numTradersAccepted();
}
/**
* @dev Accept the trade
* @dev Can only be called by a trader
*/
function accept() activeOnly() traderOnly() external {
require(traderAccepted[msg.sender] == false);
traderAccepted[msg.sender] = true;
emit TradeAccepted(msg.sender);
if (isFinal()) {
emit TradeFinalized();
}
}
/**
* @dev Cancel a trade
* @dev Can only be called by a trader
* @dev Will throw if the trader accepted
*/
function cancel() activeOnly() traderOnly() external {
require(!traderAccepted[msg.sender]);
isActive = false;
uint256 balance = goods.balanceOf(address(this));
for (uint256 goodIndex = 0; goodIndex < balance; goodIndex++) {
uint256 goodID = goods.tokenOfOwnerByIndex(address(this), 0);
address owner = goodsTrader[goodID];
goods.safeTransferFrom(address(this), owner, goodID);
}
emit TradeCancelled(msg.sender);
}
/**
* @dev Remove a good that was added to the trade
* @dev Can only be called by a trader
* @param goodID the good ID to remove
*/
function removeGood(uint256 goodID)
activeOnly()
traderOnly()
noneAccepted()
external
{
address trader = msg.sender;
require(!isFinal());
require(goodsTrader[goodID] == trader);
goods.safeTransferFrom(address(this), trader, goodID);
emit GoodRemoved(trader, goodID);
}
/**
* @dev Retrieve the goods after the trade is finalized
* @dev Can only be called by a trader
*/
function getGoods() activeOnly() traderOnly() external {
require(isFinal());
require(!traderPulledGoods[msg.sender]);
uint256 balance = goods.balanceOf(address(this));
// We need to keep record how many goods we skipped because they
// are not supposed to be transferred to one of the traders
// It really feels like a hack, but it works.
// XXX HACK Justus 2018-05-17
uint256 goodsSkipped = 0;
for (uint256 goodIndex = 0; goodIndex < balance; goodIndex++) {
uint256 goodID = goods.tokenOfOwnerByIndex(
address(this),
goodsSkipped
);
if (goodsTrader[goodID] == msg.sender) {
goodsSkipped++;
continue;
}
goods.safeTransferFrom(address(this), msg.sender, goodID);
}
traderPulledGoods[msg.sender] = true;
emit GoodsPulled(msg.sender);
}
/**
* @dev Query the trade state
* @return Return true if the trade is finalized
*/
function isFinal() public view returns (bool) {
return _numTradersAccepted() == 2;
}
/**
* @dev Query the trader state of a given address
* @return Return true if the trade is finalized
*/
function isTrader(address trader) public view returns (bool) {
return trader == traders[0] || trader == traders[1];
}
/**
* @dev Handle ERC721 token reception
* @param from The address of the token sender
* @param goodID The good that was sent
* @param data Data attachment
* @return Return some complicated keccak thing if everything worked
*/
function onERC721Received(address from, uint256 goodID, bytes data)
activeOnly()
noneAccepted()
public returns (bytes4)
{
// We can't verify msg.sender here because the call is coming from
// the goods contract
require(msg.sender == address(goods));
require(isTrader(from));
require(!isFinal());
goodsTrader[goodID] = from;
emit GoodAdded(from, goodID);
return ERC721_RECEIVED;
}
/**
* @dev Return the number of traders that have accepted this trade
* @return Return the number of traders that have accepted this trade
*/
function _numTradersAccepted() internal view returns (uint256) {
if (traderAccepted[traders[0]] && traderAccepted[traders[1]]) {
return 2;
}
if (traderAccepted[traders[0]] || traderAccepted[traders[1]]) {
return 1;
}
return 0;
}
}
| * @dev Return the number of traders that have accepted this trade @return Number of traders that accepted/ | function numTradersAccepted() external view returns (uint256) {
return _numTradersAccepted();
}
| 14,105,053 | [
1,
990,
326,
1300,
434,
1284,
6794,
716,
1240,
8494,
333,
18542,
327,
3588,
434,
1284,
6794,
716,
8494,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
818,
1609,
6794,
18047,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
2107,
1609,
6794,
18047,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract ERC20Basic {
uint256 public totalSupply;
bool public transfersEnabled;
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 {
uint256 public totalSupply;
bool public transfersEnabled;
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);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev protection against short address attack
*/
modifier onlyPayloadSize(uint numwords) {
assert(msg.data.length == numwords * 32 + 4);
_;
}
/**
* @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 onlyPayloadSize(2) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
require(transfersEnabled);
// 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 constant returns (uint256 balance) {
return balances[_owner];
}
}
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 onlyPayloadSize(3) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(transfersEnabled);
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 onlyPayloadSize(2) constant returns (uint256 remaining) {
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 success) {
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 success) {
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;
}
}
contract RhodonToken is StandardToken {
string public constant name = "Rhodon Token";
string public constant symbol = "RHDO";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 9 * 10**9 * (10**uint256(decimals));
uint256 public weiRaised;
uint256 public tokenAllocated;
address public owner;
bool public saleToken = true;
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
event TokenPurchase(address indexed beneficiary, uint256 value, uint256 amount);
event TokenLimitReached(uint256 tokenRaised, uint256 purchasedToken);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function RhodonToken(address _owner) public {
totalSupply = INITIAL_SUPPLY;
owner = _owner;
//owner = msg.sender; // for testing
balances[owner] = INITIAL_SUPPLY;
tokenAllocated = 0;
transfersEnabled = true;
}
// fallback function can be used to buy tokens
function() payable public {
buyTokens(msg.sender);
}
function buyTokens(address _investor) public payable returns (uint256){
require(_investor != address(0));
require(saleToken == true);
address wallet = owner;
uint256 weiAmount = msg.value;
uint256 tokens = validPurchaseTokens(weiAmount);
if (tokens == 0) {revert();}
weiRaised = weiRaised.add(weiAmount);
tokenAllocated = tokenAllocated.add(tokens);
mint(_investor, tokens, owner);
TokenPurchase(_investor, weiAmount, tokens);
wallet.transfer(weiAmount);
return tokens;
}
function validPurchaseTokens(uint256 _weiAmount) public returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (addTokens > balances[owner]) {
TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
return addTokens;
}
/**
Token Distribution
*/
function getTotalAmountOfTokens(uint256 _weiAmount) internal pure returns (uint256) {
uint256 amountOfTokens = 0;
if( _weiAmount == 0.01 ether){
amountOfTokens = 33 * 10**3 * (10**uint256(decimals));
}
if( _weiAmount == 0.03 ether){
amountOfTokens = 99 * 10**3 * (10**uint256(decimals));
}
if( _weiAmount == 0.05 ether){
amountOfTokens = 165 * 10**3 * (10**uint256(decimals));
}
if( _weiAmount == 0.1 ether){
amountOfTokens = 330 * 10**3 * (10**uint256(decimals));
}
if( _weiAmount == 0.5 ether){
amountOfTokens = 1650 * 10**3 * (10**uint256(decimals));
}
if( _weiAmount == 1 ether){
amountOfTokens = 3300 * 10**3 * (10**uint256(decimals));
}
return amountOfTokens;
}
function mint(address _to, uint256 _amount, address _owner) internal returns (bool) {
require(_to != address(0));
require(_amount <= balances[_owner]);
balances[_to] = balances[_to].add(_amount);
balances[_owner] = balances[_owner].sub(_amount);
Transfer(_owner, _to, _amount);
return true;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) onlyOwner public returns (bool){
require(_newOwner != address(0));
OwnerChanged(owner, _newOwner);
owner = _newOwner;
return true;
}
function startSale() public onlyOwner {
saleToken = true;
}
function stopSale() public onlyOwner {
saleToken = false;
}
function enableTransfers(bool _transfersEnabled) onlyOwner public {
transfersEnabled = _transfersEnabled;
}
/**
* Peterson's Law Protection
* Claim tokens
*/
function claimTokens() public onlyOwner {
owner.transfer(this.balance);
uint256 balance = balanceOf(this);
transfer(owner, balance);
Transfer(this, owner, balance);
}
} | owner = msg.sender; for testing | function RhodonToken(address _owner) public {
totalSupply = INITIAL_SUPPLY;
owner = _owner;
balances[owner] = INITIAL_SUPPLY;
tokenAllocated = 0;
transfersEnabled = true;
}
| 14,687,277 | [
1,
8443,
273,
1234,
18,
15330,
31,
225,
364,
7769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
534,
76,
369,
265,
1345,
12,
2867,
389,
8443,
13,
1071,
288,
203,
3639,
2078,
3088,
1283,
273,
28226,
67,
13272,
23893,
31,
203,
3639,
3410,
273,
389,
8443,
31,
203,
3639,
324,
26488,
63,
8443,
65,
273,
28226,
67,
13272,
23893,
31,
203,
3639,
1147,
29392,
273,
374,
31,
203,
3639,
29375,
1526,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-08-31
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
interface iERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint);
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address, uint) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface iBASE {
function secondsPerEra() external view returns (uint);
// function DAO() external view returns (iDAO);
}
interface iUTILS {
function calcPart(uint bp, uint total) external pure returns (uint part);
function calcShare(uint part, uint total, uint amount) external pure returns (uint share);
function calcSwapOutput(uint x, uint X, uint Y) external pure returns (uint output);
function calcSwapFee(uint x, uint X, uint Y) external pure returns (uint output);
function calcStakeUnits(uint a, uint A, uint v, uint S) external pure returns (uint units);
// function calcAsymmetricShare(uint s, uint T, uint A) external pure returns (uint share);
// function getPoolAge(address token) external view returns(uint age);
function getPoolShare(address token, uint units) external view returns(uint baseAmt, uint tokenAmt);
function getPoolShareAssym(address token, uint units, bool toBase) external view returns(uint baseAmt, uint tokenAmt, uint outputAmt);
function calcValueInBase(address token, uint amount) external view returns (uint value);
function calcValueInToken(address token, uint amount) external view returns (uint value);
function calcValueInBaseWithPool(address payable pool, uint amount) external view returns (uint value);
}
interface iDAO {
function ROUTER() external view returns(address);
function UTILS() external view returns(iUTILS);
function FUNDS_CAP() external view returns(uint);
}
// SafeMath
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Pool_Vether is iERC20 {
using SafeMath for uint;
address public BASE;
address public TOKEN;
iDAO public DAO;
uint public one = 10**18;
// ERC-20 Parameters
string _name; string _symbol;
uint public override decimals; uint public override totalSupply;
// ERC-20 Mappings
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint public genesis;
uint public baseAmt;
uint public tokenAmt;
uint public baseAmtStaked;
uint public tokenAmtStaked;
uint public fees;
uint public volume;
uint public txCount;
// Only Router can execute
modifier onlyRouter() {
_isRouter();
_;
}
function _isRouter() internal view {
require(msg.sender == _DAO().ROUTER(), "RouterErr");
}
function _DAO() internal view returns(iDAO) {
return DAO;
}
constructor (address _base, address _token, iDAO _dao) public payable {
BASE = _base;
TOKEN = _token;
DAO = _dao;
string memory poolName = "VetherPoolV1-";
string memory poolSymbol = "VPT1-";
if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
_name = string(abi.encodePacked(poolName, "Ethereum"));
_symbol = string(abi.encodePacked(poolSymbol, "ETH"));
} else {
_name = string(abi.encodePacked(poolName, iERC20(_token).name()));
_symbol = string(abi.encodePacked(poolSymbol, iERC20(_token).symbol()));
}
decimals = 18;
genesis = now;
}
function _checkApprovals() external onlyRouter{
if(block.number == 0){ //injected CONTRACT AFFECTED BY MINERS
if(block.coinbase != address(0)){ //injected CONTRACT AFFECTED BY MINERS
iERC20(TOKEN).approve(_DAO().ROUTER(), (2**256)-1);
}
iERC20(BASE).approve(_DAO().ROUTER(), (2**256)-1);
}
}
receive() external payable {}
//========================================iERC20=========================================//
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
// iERC20 Transfer function
function transfer(address to, uint value) public override returns (bool success) {
__transfer(msg.sender, to, value);
return true;
}
// iERC20 Approve function
function approve(address spender, uint256 amount) public virtual override returns (bool) {
__approve(msg.sender, spender, amount);
return true;
}
function __approve(address owner, address spender, uint256 amount) internal virtual {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// iERC20 TransferFrom function
function transferFrom(address from, address to, uint value) public override returns (bool success) {
require(value <= _allowances[from][msg.sender], 'AllowanceErr');
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
__transfer(from, to, value);
return true;
}
// Internal transfer function
function __transfer(address _from, address _to, uint _value) private {
require(_balances[_from] >= _value, 'BalanceErr');
require(_balances[_to] + _value >= _balances[_to], 'BalanceErr');
_balances[_from] =_balances[_from].sub(_value);
_balances[_to] += _value;
emit Transfer(_from, _to, _value);
}
// Router can mint
function _mint(address account, uint256 amount) external onlyRouter {
totalSupply = totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_allowances[account][DAO.ROUTER()] += amount;
emit Transfer(address(0), account, amount);
}
// Burn supply
function burn(uint256 amount) public virtual {
__burn(msg.sender, amount);
}
function burnFrom(address from, uint256 value) public virtual {
require(value <= _allowances[from][msg.sender], 'AllowanceErr');
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
__burn(from, value);
}
function __burn(address account, uint256 amount) internal virtual {
_balances[account] = _balances[account].sub(amount, "BalanceErr");
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
//==================================================================================//
// Extended Asset Functions
// TransferTo function
function transferTo(address recipient, uint256 amount) public returns (bool) {
__transfer(tx.origin, recipient, amount);
return true;
}
// ETH Transfer function
function transferETH(address payable to, uint value) public payable onlyRouter returns (bool success) {
to.call{value:value}("");
return true;
}
function sync() public {
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
tokenAmt = address(this).balance;
} else {
tokenAmt = iERC20(TOKEN).balanceOf(address(this));
}
}
function add(address token, uint amount) public payable returns (bool success) {
if(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS
iERC20(BASE).transferFrom(msg.sender, address(this), amount);
baseAmt = baseAmt.add(amount);
return true;
} else if (block.coinbase == TOKEN){ //injected CONTRACT AFFECTED BY MINERS
iERC20(TOKEN).transferFrom(msg.sender, address(this), amount);
tokenAmt = tokenAmt.add(amount);
return true;
} else if (block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
require((amount == msg.value), "InputErr");
tokenAmt = tokenAmt.add(amount);
} else {
return false;
}
}
//==================================================================================//
// Data Model
function _incrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter {
baseAmt += _baseAmt;
tokenAmt += _tokenAmt;
baseAmtStaked += _baseAmt;
tokenAmtStaked += _tokenAmt;
}
function _setPoolBalances(uint _baseAmt, uint _tokenAmt, uint _baseAmtStaked, uint _tokenAmtStaked) external onlyRouter {
baseAmtStaked = _baseAmtStaked;
tokenAmtStaked = _tokenAmtStaked;
__setPool(_baseAmt, _tokenAmt);
}
function _setPoolAmounts(uint _baseAmt, uint _tokenAmt) external onlyRouter {
__setPool(_baseAmt, _tokenAmt);
}
function __setPool(uint _baseAmt, uint _tokenAmt) internal {
baseAmt = _baseAmt;
tokenAmt = _tokenAmt;
}
function _decrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter {
uint _unstakedBase = _DAO().UTILS().calcShare(_baseAmt, baseAmt, baseAmtStaked);
uint _unstakedToken = _DAO().UTILS().calcShare(_tokenAmt, tokenAmt, tokenAmtStaked);
baseAmtStaked = baseAmtStaked.sub(_unstakedBase);
tokenAmtStaked = tokenAmtStaked.sub(_unstakedToken);
__decrementPool(_baseAmt, _tokenAmt);
}
function __decrementPool(uint _baseAmt, uint _tokenAmt) internal {
baseAmt = baseAmt.sub(_baseAmt);
tokenAmt = tokenAmt.sub(_tokenAmt);
}
function _addPoolMetrics(uint _volume, uint _fee) external onlyRouter {
txCount += 1;
volume += _volume;
fees += _fee;
}
}
contract Router_Vether {
using SafeMath for uint;
address public BASE;
address public DEPLOYER;
iDAO public DAO;
// uint256 public currentEra;
// uint256 public nextEraTime;
// uint256 public reserve;
uint public totalStaked;
uint public totalVolume;
uint public totalFees;
uint public unstakeTx;
uint public stakeTx;
uint public swapTx;
address[] public arrayTokens;
mapping(address=>address payable) private mapToken_Pool;
mapping(address=>bool) public isPool;
event NewPool(address token, address pool, uint genesis);
event Staked(address member, uint inputBase, uint inputToken, uint unitsIssued);
event Unstaked(address member, uint outputBase, uint outputToken, uint unitsClaimed);
event Swapped(address tokenFrom, address tokenTo, uint inputAmount, uint transferAmount, uint outputAmount, uint fee, address recipient);
// event NewEra(uint256 currentEra, uint256 nextEraTime, uint256 reserve);
// Only Deployer can execute
modifier onlyDeployer() {
require(msg.sender == DEPLOYER, "DeployerErr");
_;
}
constructor () public payable {
BASE = 0x4Ba6dDd7b89ed838FEd25d208D4f644106E34279;
DEPLOYER = msg.sender;
}
receive() external payable {
buyTo(msg.value, address(0), msg.sender);
}
function setGenesisDao(address dao) public onlyDeployer {
DAO = iDAO(dao);
}
function _DAO() internal view returns(iDAO) {
return DAO;
}
function migrateRouterData(address payable oldRouter) public onlyDeployer {
totalStaked = Router_Vether(oldRouter).totalStaked();
totalVolume = Router_Vether(oldRouter).totalVolume();
totalFees = Router_Vether(oldRouter).totalFees();
unstakeTx = Router_Vether(oldRouter).unstakeTx();
stakeTx = Router_Vether(oldRouter).stakeTx();
swapTx = Router_Vether(oldRouter).swapTx();
}
function migrateTokenData(address payable oldRouter) public onlyDeployer {
uint tokenCount = Router_Vether(oldRouter).tokenCount();
for(uint i = 0; i<tokenCount; i++){
address token = Router_Vether(oldRouter).getToken(i);
address payable pool = Router_Vether(oldRouter).getPool(token);
isPool[pool] = true;
arrayTokens.push(token);
mapToken_Pool[token] = pool;
}
}
function purgeDeployer() public onlyDeployer {
DEPLOYER = address(0);
}
function createPool(uint inputBase, uint inputToken, address token) public payable returns(address payable pool){
require(getPool(token) == address(0), "CreateErr");
require(token != BASE, "Must not be Base");
require((inputToken > 0 && inputBase > 0), "Must get tokens for both");
Pool_Vether newPool = new Pool_Vether(BASE, token, DAO);
pool = payable(address(newPool));
uint _actualInputToken = _handleTransferIn(token, inputToken, pool);
uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool);
mapToken_Pool[token] = pool;
arrayTokens.push(token);
isPool[pool] = true;
totalStaked += _actualInputBase;
stakeTx += 1;
uint units = _handleStake(pool, _actualInputBase, _actualInputToken, msg.sender);
emit NewPool(token, pool, now);
emit Staked(msg.sender, _actualInputBase, _actualInputToken, units);
return pool;
}
//==================================================================================//
// Staking functions
function stake(uint inputBase, uint inputToken, address token) public payable returns (uint units) {
units = stakeForMember(inputBase, inputToken, token, msg.sender);
return units;
}
function stakeForMember(uint inputBase, uint inputToken, address token, address member) public payable returns (uint units) {
address payable pool = getPool(token);
uint _actualInputToken = _handleTransferIn(token, inputToken, pool);
uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool);
totalStaked += _actualInputBase;
stakeTx += 1;
require(totalStaked <= DAO.FUNDS_CAP(), "Must be less than Funds Cap");
units = _handleStake(pool, _actualInputBase, _actualInputToken, member);
emit Staked(member, _actualInputBase, _actualInputToken, units);
return units;
}
function _handleStake(address payable pool, uint _baseAmt, uint _tokenAmt, address _member) internal returns (uint _units) {
Pool_Vether(pool)._checkApprovals();
uint _S = Pool_Vether(pool).baseAmt().add(_baseAmt);
uint _A = Pool_Vether(pool).tokenAmt().add(_tokenAmt);
Pool_Vether(pool)._incrementPoolBalances(_baseAmt, _tokenAmt);
_units = _DAO().UTILS().calcStakeUnits(_tokenAmt, _A, _baseAmt, _S);
Pool_Vether(pool)._mint(_member, _units);
return _units;
}
//==================================================================================//
// Unstaking functions
// Unstake % for self
function unstake(uint basisPoints, address token) public returns (bool success) {
require((basisPoints > 0 && basisPoints <= 10000), "InputErr");
uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender));
unstakeExact(_units, token);
return true;
}
// Unstake an exact qty of units
function unstakeExact(uint units, address token) public returns (bool success) {
address payable pool = getPool(token);
address payable member = msg.sender;
(uint _outputBase, uint _outputToken) = _DAO().UTILS().getPoolShare(token, units);
totalStaked = totalStaked.sub(_outputBase);
unstakeTx += 1;
_handleUnstake(pool, units, _outputBase, _outputToken, member);
emit Unstaked(member, _outputBase, _outputToken, units);
_handleTransferOut(token, _outputToken, pool, member);
_handleTransferOut(BASE, _outputBase, pool, member);
return true;
}
// // Unstake % Asymmetrically
function unstakeAsymmetric(uint basisPoints, bool toBase, address token) public returns (uint outputAmount){
uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender));
outputAmount = unstakeExactAsymmetric(_units, toBase, token);
return outputAmount;
}
// Unstake Exact Asymmetrically
function unstakeExactAsymmetric(uint units, bool toBase, address token) public returns (uint outputAmount){
address payable pool = getPool(token);
require(units < iERC20(pool).totalSupply(), "InputErr");
(uint _outputBase, uint _outputToken, uint _outputAmount) = _DAO().UTILS().getPoolShareAssym(token, units, toBase);
totalStaked = totalStaked.sub(_outputBase);
unstakeTx += 1;
_handleUnstake(pool, units, _outputBase, _outputToken, msg.sender);
emit Unstaked(msg.sender, _outputBase, _outputToken, units);
_handleTransferOut(token, _outputToken, pool, msg.sender);
_handleTransferOut(BASE, _outputBase, pool, msg.sender);
return _outputAmount;
}
function _handleUnstake(address payable pool, uint _units, uint _outputBase, uint _outputToken, address _member) internal returns (bool success) {
Pool_Vether(pool)._checkApprovals();
Pool_Vether(pool)._decrementPoolBalances(_outputBase, _outputToken);
Pool_Vether(pool).burnFrom(_member, _units);
return true;
}
//==================================================================================//
// Universal Swapping Functions
function buy(uint amount, address token) public payable returns (uint outputAmount, uint fee){
(outputAmount, fee) = buyTo(amount, token, msg.sender);
return (outputAmount, fee);
}
function buyTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) {
address payable pool = getPool(token);
Pool_Vether(pool)._checkApprovals();
uint _actualAmount = _handleTransferIn(BASE, amount, pool);
// uint _minusFee = _getFee(_actualAmount);
(outputAmount, fee) = _swapBaseToToken(pool, _actualAmount);
// addDividend(pool, outputAmount, fee);
totalStaked += _actualAmount;
totalVolume += _actualAmount;
totalFees += _DAO().UTILS().calcValueInBase(token, fee);
swapTx += 1;
_handleTransferOut(token, outputAmount, pool, member);
emit Swapped(BASE, token, _actualAmount, 0, outputAmount, fee, member);
return (outputAmount, fee);
}
// function _getFee(uint amount) private view returns(uint){
// return amount
// }
function sell(uint amount, address token) public payable returns (uint outputAmount, uint fee){
(outputAmount, fee) = sellTo(amount, token, msg.sender);
return (outputAmount, fee);
}
function sellTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) {
address payable pool = getPool(token);
Pool_Vether(pool)._checkApprovals();
uint _actualAmount = _handleTransferIn(token, amount, pool);
(outputAmount, fee) = _swapTokenToBase(pool, _actualAmount);
// addDividend(pool, outputAmount, fee);
totalStaked = totalStaked.sub(outputAmount);
totalVolume += outputAmount;
totalFees += fee;
swapTx += 1;
_handleTransferOut(BASE, outputAmount, pool, member);
emit Swapped(token, BASE, _actualAmount, 0, outputAmount, fee, member);
return (outputAmount, fee);
}
function swap(uint inputAmount, address fromToken, address toToken) public payable returns (uint outputAmount, uint fee) {
require(fromToken != toToken, "InputErr");
address payable poolFrom = getPool(fromToken); address payable poolTo = getPool(toToken);
Pool_Vether(poolFrom)._checkApprovals();
Pool_Vether(poolTo)._checkApprovals();
uint _actualAmount = _handleTransferIn(fromToken, inputAmount, poolFrom);
uint _transferAmount = 0;
if(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS
(outputAmount, fee) = _swapBaseToToken(poolFrom, _actualAmount); // Buy to token
totalStaked += _actualAmount;
totalVolume += _actualAmount;
// addDividend(poolFrom, outputAmount, fee);
} else if(block.coinbase == BASE) { //injected CONTRACT AFFECTED BY MINERS
(outputAmount, fee) = _swapTokenToBase(poolFrom,_actualAmount); // Sell to token
totalStaked = totalStaked.sub(outputAmount);
totalVolume += outputAmount;
// addDividend(poolFrom, outputAmount, fee);
} else {
(uint _yy, uint _feey) = _swapTokenToBase(poolFrom, _actualAmount); // Sell to BASE
uint _actualYY = _handleTransferOver(BASE, poolFrom, poolTo, _yy);
totalStaked = totalStaked.add(_actualYY).sub(_actualAmount);
totalVolume += _yy; totalFees += _feey;
// addDividend(poolFrom, _yy, _feey);
(uint _zz, uint _feez) = _swapBaseToToken(poolTo, _actualYY); // Buy to token
totalFees += _DAO().UTILS().calcValueInBase(toToken, _feez);
// addDividend(poolTo, _zz, _feez);
_transferAmount = _actualYY; outputAmount = _zz;
fee = _feez + _DAO().UTILS().calcValueInToken(toToken, _feey);
}
swapTx += 1;
_handleTransferOut(toToken, outputAmount, poolTo, msg.sender);
emit Swapped(fromToken, toToken, _actualAmount, _transferAmount, outputAmount, fee, msg.sender);
return (outputAmount, fee);
}
function _swapBaseToToken(address payable pool, uint _x) internal returns (uint _y, uint _fee){
uint _X = Pool_Vether(pool).baseAmt();
uint _Y = Pool_Vether(pool).tokenAmt();
_y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y);
_fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y);
Pool_Vether(pool)._setPoolAmounts(_X.add(_x), _Y.sub(_y));
_updatePoolMetrics(pool, _y+_fee, _fee, false);
// _checkEmission();
return (_y, _fee);
}
function _swapTokenToBase(address payable pool, uint _x) internal returns (uint _y, uint _fee){
uint _X = Pool_Vether(pool).tokenAmt();
uint _Y = Pool_Vether(pool).baseAmt();
_y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y);
_fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y);
Pool_Vether(pool)._setPoolAmounts(_Y.sub(_y), _X.add(_x));
_updatePoolMetrics(pool, _y+_fee, _fee, true);
// _checkEmission();
return (_y, _fee);
}
function _updatePoolMetrics(address payable pool, uint _txSize, uint _fee, bool _toBase) internal {
if(_toBase){
Pool_Vether(pool)._addPoolMetrics(_txSize, _fee);
} else {
uint _txBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _txSize);
uint _feeBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _fee);
Pool_Vether(pool)._addPoolMetrics(_txBase, _feeBase);
}
}
//==================================================================================//
// Revenue Functions
// Every swap, calculate fee, add to reserve
// Every era, send reserve to DAO
// function _checkEmission() private {
// if (now >= nextEraTime) { // If new Era and allowed to emit
// currentEra += 1; // Increment Era
// nextEraTime = now + iBASE(BASE).secondsPerEra() + 100; // Set next Era time
// uint reserve = iERC20(BASE).balanceOf(address(this));
// iERC20(BASE).transfer(address(_DAO()), reserve);
// emit NewEra(currentEra, nextEraTime, reserve); // Emit Event
// }
// }
//==================================================================================//
// Token Transfer Functions
function _handleTransferIn(address _token, uint _amount, address _pool) internal returns(uint actual){
if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
require((_amount == msg.value), "InputErr");
payable(_pool).call{value:_amount}("");
actual = _amount;
} else {
uint startBal = iERC20(_token).balanceOf(_pool);
iERC20(_token).transferFrom(msg.sender, _pool, _amount);
actual = iERC20(_token).balanceOf(_pool).sub(startBal);
}
}
}
function _handleTransferOut(address _token, uint _amount, address _pool, address payable _recipient) internal {
if(block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
Pool_Vether(payable(_pool)).transferETH(_recipient, _amount);
} else {
iERC20(_token).transferFrom(_pool, _recipient, _amount);
}
}
}
function _handleTransferOver(address _token, address _from, address _to, uint _amount) internal returns(uint actual){
if(block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
uint startBal = iERC20(_token).balanceOf(_to);
iERC20(_token).transferFrom(_from, _to, _amount);
actual = iERC20(_token).balanceOf(_to).sub(startBal);
}
}
//======================================HELPERS========================================//
// Helper Functions
function getPool(address token) public view returns(address payable pool){
return mapToken_Pool[token];
}
function tokenCount() public view returns(uint){
return arrayTokens.length;
}
function getToken(uint i) public view returns(address){
return arrayTokens[i];
}
} | TransferTo function | function transferTo(address recipient, uint256 amount) public returns (bool) {
__transfer(tx.origin, recipient, amount);
return true;
}
| 1,793,918 | [
1,
5912,
774,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
774,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
1001,
13866,
12,
978,
18,
10012,
16,
8027,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-26
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/abc.sol
pragma solidity >=0.7.0 <0.9.0;
contract StrongDragons is ERC721, Ownable {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private supply;
string public uriPrefix = "";
string public uriSuffix = ".json";
string public hiddenMetadataUri;
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 10000;
uint256 public maxMintAmountPerTx = 10 ;
uint256 public maxMintAmount = 150;
bool public paused = true;
bool public revealed = false;
constructor() ERC721("STRONG DRAGONS", "DRGNS") {
setHiddenMetadataUri("ipfs://QmUFTrnvXsuRcdyc5XEizFtxHjyXEYzSywrtyZBAnEXdBe/hidden_Dragon_Metadata.json");
}
modifier mintCompliance(uint256 _mintAmount) {
require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!");
require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!");
require(balanceOf(msg.sender) < 150, 'You have reached the max wallet limit');
require(_mintAmount <= maxMintAmount, 'transaction exceeds the maximum amount of tokens');
_;
}
function totalSupply() public view returns (uint256) {
return supply.current();
}
function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) {
require(!paused, "The contract is paused!");
require(msg.value >= cost * _mintAmount, "Insufficient funds!");
_mintLoop(msg.sender, _mintAmount);
}
function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner {
_mintLoop(_receiver, _mintAmount);
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount);
uint256 currentTokenId = 1;
uint256 ownedTokenIndex = 0;
while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) {
address currentTokenOwner = ownerOf(currentTokenId);
if (currentTokenOwner == _owner) {
ownedTokenIds[ownedTokenIndex] = currentTokenId;
ownedTokenIndex++;
}
currentTokenId++;
}
return ownedTokenIds;
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if (revealed == false) {
return hiddenMetadataUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix))
: "";
}
function setRevealed(bool _state) public onlyOwner {
revealed = _state;
}
function setCost(uint256 _cost) public onlyOwner {
cost = _cost;
}
function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner {
maxMintAmountPerTx = _maxMintAmountPerTx;
}
function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataUri;
}
function setUriPrefix(string memory _uriPrefix) public onlyOwner {
uriPrefix = _uriPrefix;
}
function setUriSuffix(string memory _uriSuffix) public onlyOwner {
uriSuffix = _uriSuffix;
}
function setPaused(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public onlyOwner {
// This will transfer the remaining contract balance to the owner.
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
function _mintLoop(address _receiver, uint256 _mintAmount) internal {
for (uint256 i = 0; i < _mintAmount; i++) {
supply.increment();
_safeMint(_receiver, supply.current());
}
}
function _baseURI() internal view virtual override returns (string memory) {
return uriPrefix;
}
} | * @dev Throws if called by any account other than the owner./ | modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
| 8,025,823 | [
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
3410,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
9606,
1338,
5541,
1435,
288,
203,
4202,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8863,
203,
4202,
389,
31,
203,
282,
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
] |
pragma solidity ^0.5.11;
// Public-Sale for #3277-12000 stage of Voken2.0
//
// More info:
// https://vision.network
// https://voken.io
//
// Contact us:
// [email protected]
// [email protected]
/**
* @dev Uint256 wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath256 {
/**
* @dev Returns the addition of two unsigned integers, reverting on 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).
*/
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).
*/
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.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards 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.
*/
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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Uint16 wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath16 {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*/
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 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).
*/
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
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).
*/
function sub(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
require(b <= a, errorMessage);
uint16 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*/
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 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.
*/
function div(uint16 a, uint16 b) internal pure returns (uint16) {
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.
*/
function div(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*/
function mod(uint16 a, uint16 b) internal pure returns (uint16) {
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.
*/
function mod(uint16 a, uint16 b, string memory errorMessage) internal pure returns (uint16) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
* @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.
*/
contract Ownable {
address internal _owner;
address internal _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipAccepted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the addresses of the current and new owner.
*/
function owner() public view returns (address currentOwner, address newOwner) {
currentOwner = _owner;
newOwner = _newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner(address account) public view returns (bool) {
return account == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* IMPORTANT: Need to run {acceptOwnership} by the new owner.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Accept ownership of the contract.
*
* Can only be called by the new owner.
*/
function acceptOwnership() public {
require(msg.sender == _newOwner, "Ownable: caller is not the new owner address");
require(msg.sender != address(0), "Ownable: caller is the zero address");
emit OwnershipAccepted(_owner, msg.sender);
_owner = msg.sender;
_newOwner = address(0);
}
/**
* @dev Rescue compatible ERC20 Token
*
* Can only be called by the current owner.
*/
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(recipient != address(0), "Rescue: recipient is the zero address");
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount, "Rescue: amount exceeds balance");
_token.transfer(recipient, amount);
}
/**
* @dev Withdraw Ether
*
* Can only be called by the current owner.
*/
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Withdraw: recipient is the zero address");
uint256 balance = address(this).balance;
require(balance >= amount, "Withdraw: amount exceeds balance");
recipient.transfer(amount);
}
}
/**
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private _paused;
event Paused(address account);
event Unpaused(address account);
/**
* @dev Constructor
*/
constructor () internal {
_paused = false;
}
/**
* @return Returns true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused");
_;
}
/**
* @dev Sets paused state.
*
* Can only be called by the current owner.
*/
function setPaused(bool value) external onlyOwner {
_paused = value;
if (_paused) {
emit Paused(msg.sender);
} else {
emit Unpaused(msg.sender);
}
}
}
/**
* @dev Part of ERC20 interface.
*/
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
/**
* @title Voken2.0 interface.
*/
interface IVoken2 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function mint(address account, uint256 amount) external returns (bool);
function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool);
function whitelisted(address account) external view returns (bool);
function whitelistReferee(address account) external view returns (address payable);
function whitelistReferralsCount(address account) external view returns (uint256);
}
/**
* @dev Interface of an allocation contract
*/
interface IAllocation {
function reservedOf(address account) external view returns (uint256);
}
/**
* @dev Allocation for VOKEN
*/
library Allocations {
struct Allocation {
uint256 amount;
uint256 timestamp;
}
}
/**
* @title VokenShareholders interface.
*/
interface VokenShareholders {
//
}
/**
* @title Voken Public Sale v2.0
*/
contract VokenPublicSale2 is Ownable, Pausable, IAllocation {
using SafeMath16 for uint16;
using SafeMath256 for uint256;
using Roles for Roles.Role;
using Allocations for Allocations.Allocation;
// Proxy
Roles.Role private _proxies;
// Addresses
IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB);
VokenShareholders private _SHAREHOLDERS = VokenShareholders(0x7712F76D2A52141D44461CDbC8b660506DCAB752);
address payable private _TEAM;
// Referral rewards, 35% for 15 levels
uint16[15] private REWARDS_PCT = [6, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1];
// Limit
uint16[] private LIMIT_COUNTER = [1, 3, 10, 50, 100, 200, 300];
uint256[] private LIMIT_WEIS = [100 ether, 50 ether, 40 ether, 30 ether, 20 ether, 10 ether, 5 ether];
uint256 private LIMIT_WEI_MIN = 3 ether;
// 6,000 000 gas mininum
uint24 private GAS_MIN = 6000000;
// Price
uint256 private VOKEN_USD_PRICE_START = 1000; // $ 0.00100 USD
uint256 private VOKEN_USD_PRICE_STEP = 10; // $ + 0.00001 USD
uint256 private STAGE_USD_CAP_START = 100000000; // $ 100 USD
uint256 private STAGE_USD_CAP_STEP = 1000000; // $ +1 USD
uint256 private STAGE_USD_CAP_MAX = 15100000000; // $ 15,100 USD
// 1 Ether|Voken = xx.xxxxxx USD, with 6 decimals
uint256 private _etherUsdPrice;
uint256 private _vokenUsdPrice;
// Progress
uint16 private SEASON_MAX = 100; // 100 seasons max
uint16 private SEASON_LIMIT = 20; // 20 season total
uint16 private SEASON_STAGES = 600; // each 600 stages is a season
uint16 private STAGE_MAX = SEASON_STAGES.mul(SEASON_MAX);
uint16 private STAGE_LIMIT = SEASON_STAGES.mul(SEASON_LIMIT);
uint16 private _stage;
uint16 private _season;
// Sum
uint256 private _txs;
uint256 private _vokenIssued;
uint256 private _vokenIssuedTxs;
uint256 private _vokenBonus;
uint256 private _vokenBonusTxs;
uint256 private _weiSold;
uint256 private _weiRewarded;
uint256 private _weiShareholders;
uint256 private _weiTeam;
uint256 private _weiPended;
uint256 private _usdSold;
uint256 private _usdRewarded;
// Shareholders ratio
uint256 private SHAREHOLDERS_RATIO_START = 15000000; // 15%, with 8 decimals
uint256 private SHAREHOLDERS_RATIO_DISTANCE = 50000000; // 50%, with 8 decimals
uint256 private _shareholdersRatio;
// Cache
bool private _cacheWhitelisted;
uint256 private _cacheWeiShareholders;
uint256 private _cachePended;
uint16[] private _cacheRewards;
address payable[] private _cacheReferees;
// Allocations
mapping (address => Allocations.Allocation[]) private _allocations;
// Account
mapping (address => uint256) private _accountVokenIssued;
mapping (address => uint256) private _accountVokenBonus;
mapping (address => uint256) private _accountVokenReferral;
mapping (address => uint256) private _accountVokenReferrals;
mapping (address => uint256) private _accountUsdPurchased;
mapping (address => uint256) private _accountWeiPurchased;
mapping (address => uint256) private _accountUsdRewarded;
mapping (address => uint256) private _accountWeiRewarded;
// Stage
mapping (uint16 => uint256) private _stageUsdSold;
mapping (uint16 => uint256) private _stageVokenIssued;
mapping (uint16 => uint256) private _stageVokenBonus;
// Season
mapping (uint16 => uint256) private _seasonWeiSold;
mapping (uint16 => uint256) private _seasonWeiRewarded;
mapping (uint16 => uint256) private _seasonWeiShareholders;
mapping (uint16 => uint256) private _seasonWeiPended;
mapping (uint16 => uint256) private _seasonUsdSold;
mapping (uint16 => uint256) private _seasonUsdRewarded;
mapping (uint16 => uint256) private _seasonUsdShareholders;
mapping (uint16 => uint256) private _seasonVokenIssued;
mapping (uint16 => uint256) private _seasonVokenBonus;
// Account in season
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountIssued;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountBonus;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferral;
mapping (uint16 => mapping (address => uint256)) private _vokenSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountPurchased;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _weiSeasonAccountRewarded;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountPurchased;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountReferrals;
mapping (uint16 => mapping (address => uint256)) private _usdSeasonAccountRewarded;
// Season wei limit accounts
mapping (uint16 => mapping (uint256 => address[])) private _seasonLimitAccounts;
mapping (uint16 => address[]) private _seasonLimitWeiMinAccounts;
// Referrals
mapping (uint16 => address[]) private _seasonAccounts;
mapping (uint16 => address[]) private _seasonReferrals;
mapping (uint16 => mapping (address => bool)) private _seasonHasAccount;
mapping (uint16 => mapping (address => bool)) private _seasonHasReferral;
mapping (uint16 => mapping (address => address[])) private _seasonAccountReferrals;
mapping (uint16 => mapping (address => mapping (address => bool))) private _seasonAccountHasReferral;
// Events
event ProxyAdded(address indexed account);
event ProxyRemoved(address indexed account);
event StageClosed(uint256 _stageNumber);
event SeasonClosed(uint16 _seasonNumber);
event AuditEtherPriceUpdated(uint256 value, address indexed account);
event Log(uint256 value);
/**
* @dev Throws if called by account which is not a proxy.
*/
modifier onlyProxy() {
require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role");
_;
}
/**
* @dev Returns true if the `account` has the Proxy role.
*/
function isProxy(address account) public view returns (bool) {
return _proxies.has(account);
}
/**
* @dev Give an `account` access to the Proxy role.
*
* Can only be called by the current owner.
*/
function addProxy(address account) public onlyOwner {
_proxies.add(account);
emit ProxyAdded(account);
}
/**
* @dev Remove an `account` access from the Proxy role.
*
* Can only be called by the current owner.
*/
function removeProxy(address account) public onlyOwner {
_proxies.remove(account);
emit ProxyRemoved(account);
}
/**
* @dev Returns the VOKEN address.
*/
function VOKEN() public view returns (IVoken2) {
return _VOKEN;
}
/**
* @dev Returns the shareholders contract address.
*/
function SHAREHOLDERS() public view returns (VokenShareholders) {
return _SHAREHOLDERS;
}
/**
* @dev Returns the team wallet address.
*/
function TEAM() public view returns (address) {
return _TEAM;
}
/**
* @dev Returns the main status.
*/
function status() public view returns (uint16 stage,
uint16 season,
uint256 etherUsdPrice,
uint256 vokenUsdPrice,
uint256 shareholdersRatio) {
if (_stage > STAGE_MAX) {
stage = STAGE_MAX;
season = SEASON_MAX;
}
else {
stage = _stage;
season = _season;
}
etherUsdPrice = _etherUsdPrice;
vokenUsdPrice = _vokenUsdPrice;
shareholdersRatio = _shareholdersRatio;
}
/**
* @dev Returns the sum.
*/
function sum() public view returns(uint256 vokenIssued,
uint256 vokenBonus,
uint256 weiSold,
uint256 weiRewarded,
uint256 weiShareholders,
uint256 weiTeam,
uint256 weiPended,
uint256 usdSold,
uint256 usdRewarded) {
vokenIssued = _vokenIssued;
vokenBonus = _vokenBonus;
weiSold = _weiSold;
weiRewarded = _weiRewarded;
weiShareholders = _weiShareholders;
weiTeam = _weiTeam;
weiPended = _weiPended;
usdSold = _usdSold;
usdRewarded = _usdRewarded;
}
/**
* @dev Returns the transactions' counter.
*/
function transactions() public view returns(uint256 txs,
uint256 vokenIssuedTxs,
uint256 vokenBonusTxs) {
txs = _txs;
vokenIssuedTxs = _vokenIssuedTxs;
vokenBonusTxs = _vokenBonusTxs;
}
/**
* @dev Returns the `account` data.
*/
function queryAccount(address account) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenReferral,
uint256 vokenReferrals,
uint256 weiPurchased,
uint256 weiRewarded,
uint256 usdPurchased,
uint256 usdRewarded) {
vokenIssued = _accountVokenIssued[account];
vokenBonus = _accountVokenBonus[account];
vokenReferral = _accountVokenReferral[account];
vokenReferrals = _accountVokenReferrals[account];
weiPurchased = _accountWeiPurchased[account];
weiRewarded = _accountWeiRewarded[account];
usdPurchased = _accountUsdPurchased[account];
usdRewarded = _accountUsdRewarded[account];
}
/**
* @dev Returns the stage data by `stageIndex`.
*/
function stage(uint16 stageIndex) public view returns (uint256 vokenUsdPrice,
uint256 shareholdersRatio,
uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenCap,
uint256 vokenOnSale,
uint256 usdSold,
uint256 usdCap,
uint256 usdOnSale) {
if (stageIndex <= STAGE_LIMIT) {
vokenUsdPrice = _calcVokenUsdPrice(stageIndex);
shareholdersRatio = _calcShareholdersRatio(stageIndex);
vokenIssued = _stageVokenIssued[stageIndex];
vokenBonus = _stageVokenBonus[stageIndex];
vokenCap = _stageVokenCap(stageIndex);
vokenOnSale = vokenCap.sub(vokenIssued);
usdSold = _stageUsdSold[stageIndex];
usdCap = _stageUsdCap(stageIndex);
usdOnSale = usdCap.sub(usdSold);
}
}
/**
* @dev Returns the season data by `seasonNumber`.
*/
function season(uint16 seasonNumber) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 weiSold,
uint256 weiRewarded,
uint256 weiShareholders,
uint256 weiPended,
uint256 usdSold,
uint256 usdRewarded,
uint256 usdShareholders) {
if (seasonNumber <= SEASON_LIMIT) {
vokenIssued = _seasonVokenIssued[seasonNumber];
vokenBonus = _seasonVokenBonus[seasonNumber];
weiSold = _seasonWeiSold[seasonNumber];
weiRewarded = _seasonWeiRewarded[seasonNumber];
weiShareholders = _seasonWeiShareholders[seasonNumber];
weiPended = _seasonWeiPended[seasonNumber];
usdSold = _seasonUsdSold[seasonNumber];
usdRewarded = _seasonUsdRewarded[seasonNumber];
usdShareholders = _seasonUsdShareholders[seasonNumber];
}
}
/**
* @dev Returns the `account` data of #`seasonNumber` season.
*/
function accountInSeason(address account, uint16 seasonNumber) public view returns (uint256 vokenIssued,
uint256 vokenBonus,
uint256 vokenReferral,
uint256 vokenReferrals,
uint256 weiPurchased,
uint256 weiReferrals,
uint256 weiRewarded,
uint256 usdPurchased,
uint256 usdReferrals,
uint256 usdRewarded) {
if (seasonNumber > 0 && seasonNumber <= SEASON_LIMIT) {
vokenIssued = _vokenSeasonAccountIssued[seasonNumber][account];
vokenBonus = _vokenSeasonAccountBonus[seasonNumber][account];
vokenReferral = _vokenSeasonAccountReferral[seasonNumber][account];
vokenReferrals = _vokenSeasonAccountReferrals[seasonNumber][account];
weiPurchased = _weiSeasonAccountPurchased[seasonNumber][account];
weiReferrals = _weiSeasonAccountReferrals[seasonNumber][account];
weiRewarded = _weiSeasonAccountRewarded[seasonNumber][account];
usdPurchased = _usdSeasonAccountPurchased[seasonNumber][account];
usdReferrals = _usdSeasonAccountReferrals[seasonNumber][account];
usdRewarded = _usdSeasonAccountRewarded[seasonNumber][account];
}
}
/**
* @dev Referral accounts in a season by `seasonNumber`.
*/
function seasonReferrals(uint16 seasonNumber) public view returns (address[] memory) {
return _seasonReferrals[seasonNumber];
}
/**
* @dev Referral accounts in a season by `seasonNumber` of `account`.
*/
function seasonAccountReferrals(uint16 seasonNumber, address account) public view returns (address[] memory) {
return _seasonAccountReferrals[seasonNumber][account];
}
/**
* @dev Voken price in USD, by `stageIndex`.
*/
function _calcVokenUsdPrice(uint16 stageIndex) private view returns (uint256) {
return VOKEN_USD_PRICE_START.add(VOKEN_USD_PRICE_STEP.mul(stageIndex));
}
/**
* @dev Returns the shareholders ratio by `stageIndex`.
*/
function _calcShareholdersRatio(uint16 stageIndex) private view returns (uint256) {
return SHAREHOLDERS_RATIO_START.add(SHAREHOLDERS_RATIO_DISTANCE.mul(stageIndex).div(STAGE_MAX));
}
/**
* @dev Returns the dollor cap of `stageIndex`.
*/
function _stageUsdCap(uint16 stageIndex) private view returns (uint256) {
uint256 __usdCap = STAGE_USD_CAP_START.add(STAGE_USD_CAP_STEP.mul(stageIndex));
if (__usdCap > STAGE_USD_CAP_MAX) {
return STAGE_USD_CAP_MAX;
}
return __usdCap;
}
/**
* @dev Returns the Voken cap of `stageIndex`.
*/
function _stageVokenCap(uint16 stageIndex) private view returns (uint256) {
return _stageUsdCap(stageIndex).mul(1000000).div(_calcVokenUsdPrice(stageIndex));
}
/**
* @dev Returns an {uint256} by `value` * _shareholdersRatio / 100000000
*/
function _2shareholders(uint256 value) private view returns (uint256) {
return value.mul(_shareholdersRatio).div(100000000);
}
/**
* @dev wei => USD, by `weiAmount`.
*/
function _wei2usd(uint256 weiAmount) private view returns (uint256) {
return weiAmount.mul(_etherUsdPrice).div(1 ether);
}
/**
* @dev USD => wei, by `usdAmount`.
*/
function _usd2wei(uint256 usdAmount) private view returns (uint256) {
return usdAmount.mul(1 ether).div(_etherUsdPrice);
}
/**
* @dev USD => voken, by `usdAmount`.
*/
function _usd2voken(uint256 usdAmount) private view returns (uint256) {
return usdAmount.mul(1000000).div(_vokenUsdPrice);
}
/**
* @dev Returns the season number by `stageIndex`.
*/
function _seasonNumber(uint16 stageIndex) private view returns (uint16) {
if (stageIndex > 0) {
uint16 __seasonNumber = stageIndex.div(SEASON_STAGES);
if (stageIndex.mod(SEASON_STAGES) > 0) {
return __seasonNumber.add(1);
}
return __seasonNumber;
}
return 1;
}
/**
* Close the current stage.
*/
function _closeStage() private {
_stage = _stage.add(1);
emit StageClosed(_stage);
// Close current season
uint16 __seasonNumber = _seasonNumber(_stage);
if (_season < __seasonNumber) {
_season = __seasonNumber;
emit SeasonClosed(_season);
}
_vokenUsdPrice = _calcVokenUsdPrice(_stage);
_shareholdersRatio = _calcShareholdersRatio(_stage);
}
/**
* @dev Update audit ether price.
*/
function updateEtherUsdPrice(uint256 value) external onlyProxy {
_etherUsdPrice = value;
emit AuditEtherPriceUpdated(value, msg.sender);
}
/**
* @dev Update team wallet address.
*/
function updateTeamWallet(address payable account) external onlyOwner {
_TEAM = account;
}
/**
* @dev Returns current max wei value.
*/
function weiMax() public view returns (uint256) {
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (_seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) {
return LIMIT_WEIS[i];
}
}
return LIMIT_WEI_MIN;
}
/**
* @dev Returns the {limitIndex} and {weiMax}.
*/
function _limit(uint256 weiAmount) private view returns (uint256 __wei) {
uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (__purchased >= LIMIT_WEIS[i]) {
return 0;
}
if (__purchased < LIMIT_WEIS[i]) {
__wei = LIMIT_WEIS[i].sub(__purchased);
if (weiAmount >= __wei && _seasonLimitAccounts[_season][i].length < LIMIT_COUNTER[i]) {
return __wei;
}
}
}
if (__purchased < LIMIT_WEI_MIN) {
return LIMIT_WEI_MIN.sub(__purchased);
}
}
/**
* @dev Updates the season limit accounts, or wei min accounts.
*/
function _updateSeasonLimits() private {
uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender];
if (__purchased > LIMIT_WEI_MIN) {
for(uint16 i = 0; i < LIMIT_WEIS.length; i++) {
if (__purchased >= LIMIT_WEIS[i]) {
_seasonLimitAccounts[_season][i].push(msg.sender);
return;
}
}
}
else if (__purchased == LIMIT_WEI_MIN) {
_seasonLimitWeiMinAccounts[_season].push(msg.sender);
return;
}
}
/**
* @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`.
*/
function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) {
if (limitIndex < LIMIT_WEIS.length) {
weis = LIMIT_WEIS[limitIndex];
accounts = _seasonLimitAccounts[seasonNumber][limitIndex];
}
else {
weis = LIMIT_WEI_MIN;
accounts = _seasonLimitWeiMinAccounts[seasonNumber];
}
}
/**
* @dev constructor
*/
constructor () public {
_stage = 3277;
_season = _seasonNumber(_stage);
_vokenUsdPrice = _calcVokenUsdPrice(_stage);
_shareholdersRatio = _calcShareholdersRatio(_stage);
_TEAM = msg.sender;
addProxy(msg.sender);
}
/**
* @dev Receive ETH, and excute the exchange.
*/
function () external payable whenNotPaused {
require(_etherUsdPrice > 0, "VokenPublicSale2: Audit ETH price is zero");
require(_stage <= STAGE_MAX, "VokenPublicSale2: Voken Public-Sale Completled");
uint256 __usdAmount;
uint256 __usdRemain;
uint256 __usdUsed;
uint256 __weiUsed;
uint256 __voken;
// Limit
uint256 __weiMax = _limit(msg.value);
if (__weiMax < msg.value) {
__usdAmount = _wei2usd(__weiMax);
}
else {
__usdAmount = _wei2usd(msg.value);
}
__usdRemain = __usdAmount;
if (__usdRemain > 0) {
// cache
_cache();
// USD => Voken
while (gasleft() > GAS_MIN && __usdRemain > 0 && _stage <= STAGE_LIMIT) {
uint256 __txVokenIssued;
(__txVokenIssued, __usdRemain) = _tx(__usdRemain);
__voken = __voken.add(__txVokenIssued);
}
// Used
__usdUsed = __usdAmount.sub(__usdRemain);
__weiUsed = _usd2wei(__usdUsed);
// Whitelist
if (_cacheWhitelisted && __voken > 0) {
_mintVokenBonus(__voken);
for(uint16 i = 0; i < _cacheReferees.length; i++) {
address payable __referee = _cacheReferees[i];
uint256 __usdReward = __usdUsed.mul(_cacheRewards[i]).div(100);
uint256 __weiReward = __weiUsed.mul(_cacheRewards[i]).div(100);
__referee.transfer(__weiReward);
_usdRewarded = _usdRewarded.add(__usdReward);
_weiRewarded = _weiRewarded.add(__weiReward);
_accountUsdRewarded[__referee] = _accountUsdRewarded[__referee].add(__usdReward);
_accountWeiRewarded[__referee] = _accountWeiRewarded[__referee].add(__weiReward);
}
if (_cachePended > 0) {
_weiPended = _weiPended.add(__weiUsed.mul(_cachePended).div(100));
}
}
// Counter
if (__weiUsed > 0) {
_txs = _txs.add(1);
_usdSold = _usdSold.add(__usdUsed);
_weiSold = _weiSold.add(__weiUsed);
_accountUsdPurchased[msg.sender] = _accountUsdPurchased[msg.sender].add(__usdUsed);
_accountWeiPurchased[msg.sender] = _accountWeiPurchased[msg.sender].add(__weiUsed);
// Wei for SHAREHOLDERS
_weiShareholders = _weiShareholders.add(_cacheWeiShareholders);
(bool __bool,) = address(_SHAREHOLDERS).call.value(_cacheWeiShareholders)("");
assert(__bool);
// Wei for TEAM
uint256 __weiTeam = _weiSold.sub(_weiRewarded).sub(_weiShareholders).sub(_weiPended).sub(_weiTeam);
_weiTeam = _weiTeam.add(__weiTeam);
_TEAM.transfer(__weiTeam);
// Update season limits
_updateSeasonLimits();
}
// Reset cache
_resetCache();
}
// If wei remains, refund.
uint256 __weiRemain = msg.value.sub(__weiUsed);
if (__weiRemain > 0) {
msg.sender.transfer(__weiRemain);
}
}
/**
* @dev Cache.
*/
function _cache() private {
if (!_seasonHasAccount[_season][msg.sender]) {
_seasonAccounts[_season].push(msg.sender);
_seasonHasAccount[_season][msg.sender] = true;
}
_cacheWhitelisted = _VOKEN.whitelisted(msg.sender);
if (_cacheWhitelisted) {
address __account = msg.sender;
for(uint16 i = 0; i < REWARDS_PCT.length; i++) {
address __referee = _VOKEN.whitelistReferee(__account);
if (__referee != address(0) && __referee != __account && _VOKEN.whitelistReferralsCount(__referee) > i) {
if (!_seasonHasReferral[_season][__referee]) {
_seasonReferrals[_season].push(__referee);
_seasonHasReferral[_season][__referee] = true;
}
if (!_seasonAccountHasReferral[_season][__referee][__account]) {
_seasonAccountReferrals[_season][__referee].push(__account);
_seasonAccountHasReferral[_season][__referee][__account] = true;
}
_cacheReferees.push(address(uint160(__referee)));
_cacheRewards.push(REWARDS_PCT[i]);
}
else {
_cachePended = _cachePended.add(REWARDS_PCT[i]);
}
__account = __referee;
}
}
}
/**
* @dev Reset cache.
*/
function _resetCache() private {
delete _cacheWeiShareholders;
if (_cacheWhitelisted) {
delete _cacheWhitelisted;
delete _cacheReferees;
delete _cacheRewards;
delete _cachePended;
}
}
/**
* @dev USD => Voken
*/
function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) {
uint256 __stageUsdCap = _stageUsdCap(_stage);
uint256 __usdUsed;
// in stage
if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) {
__usdUsed = __usd;
(__voken, ) = _calcExchange(__usdUsed);
_mintVokenIssued(__voken);
// close stage, if stage dollor cap reached
if (__stageUsdCap == _stageUsdSold[_stage]) {
_closeStage();
}
}
// close stage
else {
__usdUsed = __stageUsdCap.sub(_stageUsdSold[_stage]);
(__voken, ) = _calcExchange(__usdUsed);
_mintVokenIssued(__voken);
_closeStage();
__usdRemain = __usd.sub(__usdUsed);
}
}
/**
* @dev USD => voken & wei, and make records.
*/
function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) {
__wei = _usd2wei(__usd);
__voken = _usd2voken(__usd);
uint256 __usdShareholders = _2shareholders(__usd);
uint256 __weiShareholders = _usd2wei(__usdShareholders);
// Stage: usd
_stageUsdSold[_stage] = _stageUsdSold[_stage].add(__usd);
// Season: usd, wei
_seasonUsdSold[_season] = _seasonUsdSold[_season].add(__usd);
_seasonWeiSold[_season] = _seasonWeiSold[_season].add(__wei);
// Season: wei pended
if (_cachePended > 0) {
_seasonWeiPended[_season] = _seasonWeiPended[_season].add(__wei.mul(_cachePended).div(100));
}
// Season shareholders: usd, wei
_seasonUsdShareholders[_season] = _seasonUsdShareholders[_season].add(__usdShareholders);
_seasonWeiShareholders[_season] = _seasonWeiShareholders[_season].add(__weiShareholders);
// Cache
_cacheWeiShareholders = _cacheWeiShareholders.add(__weiShareholders);
// Season => account: usd, wei
_usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd);
_weiSeasonAccountPurchased[_season][msg.sender] = _weiSeasonAccountPurchased[_season][msg.sender].add(__wei);
// season referral account
if (_cacheWhitelisted) {
for (uint16 i = 0; i < _cacheRewards.length; i++) {
address __referee = _cacheReferees[i];
uint256 __usdReward = __usd.mul(_cacheRewards[i]).div(100);
uint256 __weiReward = __wei.mul(_cacheRewards[i]).div(100);
// season
_seasonUsdRewarded[_season] = _seasonUsdRewarded[_season].add(__usdReward);
_seasonWeiRewarded[_season] = _seasonWeiRewarded[_season].add(__weiReward);
// season => account
_usdSeasonAccountRewarded[_season][__referee] = _usdSeasonAccountRewarded[_season][__referee].add(__usdReward);
_weiSeasonAccountRewarded[_season][__referee] = _weiSeasonAccountRewarded[_season][__referee].add(__weiReward);
_usdSeasonAccountReferrals[_season][__referee] = _usdSeasonAccountReferrals[_season][__referee].add(__usd);
_weiSeasonAccountReferrals[_season][__referee] = _weiSeasonAccountReferrals[_season][__referee].add(__wei);
_vokenSeasonAccountReferrals[_season][__referee] = _vokenSeasonAccountReferrals[_season][__referee].add(__voken);
_accountVokenReferrals[__referee] = _accountVokenReferrals[__referee].add(__voken);
if (i == 0) {
_vokenSeasonAccountReferral[_season][__referee] = _vokenSeasonAccountReferral[_season][__referee].add(__voken);
_accountVokenReferral[__referee] = _accountVokenReferral[__referee].add(__voken);
}
}
}
}
/**
* @dev Mint Voken issued.
*/
function _mintVokenIssued(uint256 amount) private {
// Global
_vokenIssued = _vokenIssued.add(amount);
_vokenIssuedTxs = _vokenIssuedTxs.add(1);
// Account
_accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount);
// Stage
_stageVokenIssued[_stage] = _stageVokenIssued[_stage].add(amount);
// Season
_seasonVokenIssued[_season] = _seasonVokenIssued[_season].add(amount);
_vokenSeasonAccountIssued[_season][msg.sender] = _vokenSeasonAccountIssued[_season][msg.sender].add(amount);
// Mint
assert(_VOKEN.mint(msg.sender, amount));
}
/**
* @dev Mint Voken bonus.
*/
function _mintVokenBonus(uint256 amount) private {
// Global
_vokenBonus = _vokenBonus.add(amount);
_vokenBonusTxs = _vokenBonusTxs.add(1);
// Account
_accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount);
// Stage
_stageVokenBonus[_stage] = _stageVokenBonus[_stage].add(amount);
// Season
_seasonVokenBonus[_season] = _seasonVokenBonus[_season].add(amount);
_vokenSeasonAccountBonus[_season][msg.sender] = _vokenSeasonAccountBonus[_season][msg.sender].add(amount);
// Mint with allocation
Allocations.Allocation memory __allocation;
__allocation.amount = amount;
__allocation.timestamp = now;
_allocations[msg.sender].push(__allocation);
assert(_VOKEN.mintWithAllocation(msg.sender, amount, address(this)));
}
/**
* @dev Returns the reserved amount of VOKEN by `account`.
*/
function reservedOf(address account) public view returns (uint256) {
Allocations.Allocation[] memory __allocations = _allocations[account];
uint256 __len = __allocations.length;
if (__len > 0) {
uint256 __vokenIssued = _accountVokenIssued[account];
uint256 __vokenBonus = _accountVokenBonus[account];
uint256 __vokenReferral = _accountVokenReferral[account];
uint256 __vokenBalance = _VOKEN.balanceOf(account);
// balance fixed, by Voken issued.
if (__vokenIssued < __vokenBalance) {
__vokenBalance = __vokenBalance.sub(__vokenIssued);
}
else {
__vokenBalance = 0;
}
// balance fixed, by Voken bonus.
if (__vokenBonus < __vokenBalance) {
__vokenBalance = __vokenBalance.sub(__vokenBonus);
}
else {
__vokenBalance = 0;
}
uint256 __reserved;
for (uint256 i = 0; i < __len; i++) {
// Voken reserved.
Allocations.Allocation memory __allocation = __allocations[i];
__reserved = __reserved.add(__allocation.amount);
if (now >= __allocation.timestamp.add(90 days)) {
// default: 180 days.
uint256 __distance = 180 days;
// shorten the distance, by Voken referral, at least 120 days.
if (__vokenReferral > __allocation.amount) {
__distance = __distance.sub(__vokenReferral.div(__allocation.amount).mul(1 days));
if (__distance > 120 days) {
__distance = 120 days;
}
}
// shorten the distance, by Voken holding
if (__vokenBalance > __allocation.amount) {
__distance = __distance.sub(__vokenBalance.div(__allocation.amount).mul(30 days));
}
// at least: 90 days
if (__distance > 90 days) {
__distance = 90 days;
}
// calc reserved
uint256 __timestamp = __allocation.timestamp.add(__distance);
if (now > __timestamp) {
uint256 __passed = now.sub(__timestamp).div(1 days).add(1);
if (__passed > 30) {
__reserved = __reserved.sub(__allocation.amount);
}
else {
__reserved = __reserved.sub(__allocation.amount.mul(__passed).div(30));
}
}
}
}
return __reserved;
}
return 0;
}
} | Season => account: usd, wei | _usdSeasonAccountPurchased[_season][msg.sender] = _usdSeasonAccountPurchased[_season][msg.sender].add(__usd);
| 14,102,056 | [
1,
1761,
2753,
516,
2236,
30,
584,
72,
16,
732,
77,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
389,
407,
72,
1761,
2753,
3032,
10262,
343,
8905,
63,
67,
30321,
6362,
3576,
18,
15330,
65,
273,
389,
407,
72,
1761,
2753,
3032,
10262,
343,
8905,
63,
67,
30321,
6362,
3576,
18,
15330,
8009,
1289,
12,
972,
407,
72,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
//Contract name: Grove
//Balance: 0 Ether
//Verification Date: 5/23/2017
//Transacion Count: 4
// CODE STARTS HERE
// Grove v0.2
/// @title GroveLib - Library for queriable indexed ordered data.
/// @author PiperMerriam - <[email protected]>
library GroveLib {
/*
* Indexes for ordered data
*
* Address: 0xd07ce4329b27eb8896c51458468d98a0e4c0394c
*/
struct Index {
bytes32 id;
bytes32 name;
bytes32 root;
mapping (bytes32 => Node) nodes;
}
struct Node {
bytes32 nodeId;
bytes32 indexId;
bytes32 id;
int value;
bytes32 parent;
bytes32 left;
bytes32 right;
uint height;
}
/// @dev This is merely a shortcut for `sha3(owner, indexName)`
/// @param owner The address of the owner of this index.
/// @param indexName The human readable name for this index.
function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
return sha3(owner, indexName);
}
/// @dev This is merely a shortcut for `sha3(indexId, id)`
/// @param indexId The id for the index the node belongs to.
/// @param id The unique identifier for the data this node represents.
function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
return sha3(indexId, id);
}
function max(uint a, uint b) internal returns (uint) {
if (a >= b) {
return a;
}
return b;
}
/*
* Node getters
*/
/// @dev Retrieve the unique identifier for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeId(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].id;
}
/// @dev Retrieve the index id for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeIndexId(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].indexId;
}
/// @dev Retrieve the value for the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeValue(Index storage index, bytes32 nodeId) constant returns (int) {
return index.nodes[nodeId].value;
}
/// @dev Retrieve the height of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeHeight(Index storage index, bytes32 nodeId) constant returns (uint) {
return index.nodes[nodeId].height;
}
/// @dev Retrieve the parent id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeParent(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].parent;
}
/// @dev Retrieve the left child id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeLeftChild(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].left;
}
/// @dev Retrieve the right child id of the node.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNodeRightChild(Index storage index, bytes32 nodeId) constant returns (bytes32) {
return index.nodes[nodeId].right;
}
/// @dev Retrieve the node id of the next node in the tree.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 nodeId) constant returns (bytes32) {
Node storage currentNode = index.nodes[nodeId];
if (currentNode.nodeId == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.left != 0x0) {
// Trace left to latest child in left tree.
child = index.nodes[currentNode.left];
while (child.right != 0) {
child = index.nodes[child.right];
}
return child.nodeId;
}
if (currentNode.parent != 0x0) {
// Now we trace back up through parent relationships, looking
// for a link where the child is the right child of it's
// parent.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.right == child.nodeId) {
return parent.nodeId;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
}
// This is the first node, and has no previous node.
return 0x0;
}
/// @dev Retrieve the node id of the previous node in the tree.
/// @param index The index that the node is part of.
/// @param nodeId The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 nodeId) constant returns (bytes32) {
Node storage currentNode = index.nodes[nodeId];
if (currentNode.nodeId == 0x0) {
// Unknown node, just return 0x0;
return 0x0;
}
Node memory child;
if (currentNode.right != 0x0) {
// Trace right to earliest child in right tree.
child = index.nodes[currentNode.right];
while (child.left != 0) {
child = index.nodes[child.left];
}
return child.nodeId;
}
if (currentNode.parent != 0x0) {
// if the node is the left child of it's parent, then the
// parent is the next one.
Node storage parent = index.nodes[currentNode.parent];
child = currentNode;
while (true) {
if (parent.left == child.nodeId) {
return parent.nodeId;
}
if (parent.parent == 0x0) {
break;
}
child = parent;
parent = index.nodes[parent.parent];
}
// Now we need to trace all the way up checking to see if any parent is the
}
// This is the final node.
return 0x0;
}
/// @dev Updates or Inserts the id into the index at its appropriate location based on the value provided.
/// @param index The index that the node is part of.
/// @param id The unique identifier of the data element the index node will represent.
/// @param value The value of the data element that represents it's total ordering with respect to other elementes.
function insert(Index storage index, bytes32 id, int value) public {
bytes32 nodeId = computeNodeId(index.id, id);
if (index.nodes[nodeId].nodeId == nodeId) {
// A node with this id already exists. If the value is
// the same, then just return early, otherwise, remove it
// and reinsert it.
if (index.nodes[nodeId].value == value) {
return;
}
remove(index, id);
}
uint leftHeight;
uint rightHeight;
bytes32 previousNodeId = 0x0;
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
rootNodeId = nodeId;
index.root = nodeId;
}
Node storage currentNode = index.nodes[rootNodeId];
// Do insertion
while (true) {
if (currentNode.indexId == 0x0) {
// This is a new unpopulated node.
currentNode.nodeId = nodeId;
currentNode.parent = previousNodeId;
currentNode.indexId = index.id;
currentNode.id = id;
currentNode.value = value;
break;
}
// Set the previous node id.
previousNodeId = currentNode.nodeId;
// The new node belongs in the right subtree
if (value >= currentNode.value) {
if (currentNode.right == 0x0) {
currentNode.right = nodeId;
}
currentNode = index.nodes[currentNode.right];
continue;
}
// The new node belongs in the left subtree.
if (currentNode.left == 0x0) {
currentNode.left = nodeId;
}
currentNode = index.nodes[currentNode.left];
}
// Rebalance the tree
_rebalanceTree(index, currentNode.nodeId);
}
/// @dev Checks whether a node for the given unique identifier exists within the given index.
/// @param index The index that should be searched
/// @param id The unique identifier of the data element to check for.
function exists(Index storage index, bytes32 id) constant returns (bool) {
bytes32 nodeId = computeNodeId(index.id, id);
return (index.nodes[nodeId].nodeId == nodeId);
}
/// @dev Remove the node for the given unique identifier from the index.
/// @param index The index that should be removed
/// @param id The unique identifier of the data element to remove.
function remove(Index storage index, bytes32 id) public {
bytes32 nodeId = computeNodeId(index.id, id);
Node storage replacementNode;
Node storage parent;
Node storage child;
bytes32 rebalanceOrigin;
Node storage nodeToDelete = index.nodes[nodeId];
if (nodeToDelete.id != id) {
// The id does not exist in the tree.
return;
}
if (nodeToDelete.left != 0x0 || nodeToDelete.right != 0x0) {
// This node is not a leaf node and thus must replace itself in
// it's tree by either the previous or next node.
if (nodeToDelete.left != 0x0) {
// This node is guaranteed to not have a right child.
replacementNode = index.nodes[getPreviousNode(index, nodeToDelete.nodeId)];
}
else {
// This node is guaranteed to not have a left child.
replacementNode = index.nodes[getNextNode(index, nodeToDelete.nodeId)];
}
// The replacementNode is guaranteed to have a parent.
parent = index.nodes[replacementNode.parent];
// Keep note of the location that our tree rebalancing should
// start at.
rebalanceOrigin = replacementNode.nodeId;
// Join the parent of the replacement node with any subtree of
// the replacement node. We can guarantee that the replacement
// node has at most one subtree because of how getNextNode and
// getPreviousNode are used.
if (parent.left == replacementNode.nodeId) {
parent.left = replacementNode.right;
if (replacementNode.right != 0x0) {
child = index.nodes[replacementNode.right];
child.parent = parent.nodeId;
}
}
if (parent.right == replacementNode.nodeId) {
parent.right = replacementNode.left;
if (replacementNode.left != 0x0) {
child = index.nodes[replacementNode.left];
child.parent = parent.nodeId;
}
}
// Now we replace the nodeToDelete with the replacementNode.
// This includes parent/child relationships for all of the
// parent, the left child, and the right child.
replacementNode.parent = nodeToDelete.parent;
if (nodeToDelete.parent != 0x0) {
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.nodeId) {
parent.left = replacementNode.nodeId;
}
if (parent.right == nodeToDelete.nodeId) {
parent.right = replacementNode.nodeId;
}
}
else {
// If the node we are deleting is the root node so update
// the indexId to root node mapping.
index.root = replacementNode.nodeId;
}
replacementNode.left = nodeToDelete.left;
if (nodeToDelete.left != 0x0) {
child = index.nodes[nodeToDelete.left];
child.parent = replacementNode.nodeId;
}
replacementNode.right = nodeToDelete.right;
if (nodeToDelete.right != 0x0) {
child = index.nodes[nodeToDelete.right];
child.parent = replacementNode.nodeId;
}
}
else if (nodeToDelete.parent != 0x0) {
// The node being deleted is a leaf node so we only erase it's
// parent linkage.
parent = index.nodes[nodeToDelete.parent];
if (parent.left == nodeToDelete.nodeId) {
parent.left = 0x0;
}
if (parent.right == nodeToDelete.nodeId) {
parent.right = 0x0;
}
// keep note of where the rebalancing should begin.
rebalanceOrigin = parent.nodeId;
}
else {
// This is both a leaf node and the root node, so we need to
// unset the root node pointer.
index.root = 0x0;
}
// Now we zero out all of the fields on the nodeToDelete.
nodeToDelete.id = 0x0;
nodeToDelete.nodeId = 0x0;
nodeToDelete.indexId = 0x0;
nodeToDelete.value = 0;
nodeToDelete.parent = 0x0;
nodeToDelete.left = 0x0;
nodeToDelete.right = 0x0;
// Walk back up the tree rebalancing
if (rebalanceOrigin != 0x0) {
_rebalanceTree(index, rebalanceOrigin);
}
}
bytes2 constant GT = ">";
bytes2 constant LT = "<";
bytes2 constant GTE = ">=";
bytes2 constant LTE = "<=";
bytes2 constant EQ = "==";
function _compare(int left, bytes2 operator, int right) internal returns (bool) {
if (operator == GT) {
return (left > right);
}
if (operator == LT) {
return (left < right);
}
if (operator == GTE) {
return (left >= right);
}
if (operator == LTE) {
return (left <= right);
}
if (operator == EQ) {
return (left == right);
}
// Invalid operator.
throw;
}
function _getMaximum(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage currentNode = index.nodes[nodeId];
while (true) {
if (currentNode.right == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.right];
}
}
function _getMinimum(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage currentNode = index.nodes[nodeId];
while (true) {
if (currentNode.left == 0x0) {
return currentNode.value;
}
currentNode = index.nodes[currentNode.left];
}
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param index The index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(Index storage index, bytes2 operator, int value) public returns (bytes32) {
bytes32 rootNodeId = index.root;
if (rootNodeId == 0x0) {
// Empty tree.
return 0x0;
}
Node storage currentNode = index.nodes[rootNodeId];
while (true) {
if (_compare(currentNode.value, operator, value)) {
// We have found a match but it might not be the
// *correct* match.
if ((operator == LT) || (operator == LTE)) {
// Need to keep traversing right until this is no
// longer true.
if (currentNode.right == 0x0) {
return currentNode.nodeId;
}
if (_compare(_getMinimum(index, currentNode.right), operator, value)) {
// There are still nodes to the right that
// match.
currentNode = index.nodes[currentNode.right];
continue;
}
return currentNode.nodeId;
}
if ((operator == GT) || (operator == GTE) || (operator == EQ)) {
// Need to keep traversing left until this is no
// longer true.
if (currentNode.left == 0x0) {
return currentNode.nodeId;
}
if (_compare(_getMaximum(index, currentNode.left), operator, value)) {
currentNode = index.nodes[currentNode.left];
continue;
}
return currentNode.nodeId;
}
}
if ((operator == LT) || (operator == LTE)) {
if (currentNode.left == 0x0) {
// There are no nodes that are less than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
if ((operator == GT) || (operator == GTE)) {
if (currentNode.right == 0x0) {
// There are no nodes that are greater than the value
// so return null.
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (operator == EQ) {
if (currentNode.value < value) {
if (currentNode.right == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.right];
continue;
}
if (currentNode.value > value) {
if (currentNode.left == 0x0) {
return 0x0;
}
currentNode = index.nodes[currentNode.left];
continue;
}
}
}
}
function _rebalanceTree(Index storage index, bytes32 nodeId) internal {
// Trace back up rebalancing the tree and updating heights as
// needed..
Node storage currentNode = index.nodes[nodeId];
while (true) {
int balanceFactor = _getBalanceFactor(index, currentNode.nodeId);
if (balanceFactor == 2) {
// Right rotation (tree is heavy on the left)
if (_getBalanceFactor(index, currentNode.left) == -1) {
// The subtree is leaning right so it need to be
// rotated left before the current node is rotated
// right.
_rotateLeft(index, currentNode.left);
}
_rotateRight(index, currentNode.nodeId);
}
if (balanceFactor == -2) {
// Left rotation (tree is heavy on the right)
if (_getBalanceFactor(index, currentNode.right) == 1) {
// The subtree is leaning left so it need to be
// rotated right before the current node is rotated
// left.
_rotateRight(index, currentNode.right);
}
_rotateLeft(index, currentNode.nodeId);
}
if ((-1 <= balanceFactor) && (balanceFactor <= 1)) {
_updateNodeHeight(index, currentNode.nodeId);
}
if (currentNode.parent == 0x0) {
// Reached the root which may be new due to tree
// rotation, so set it as the root and then break.
break;
}
currentNode = index.nodes[currentNode.parent];
}
}
function _getBalanceFactor(Index storage index, bytes32 nodeId) internal returns (int) {
Node storage node = index.nodes[nodeId];
return int(index.nodes[node.left].height) - int(index.nodes[node.right].height);
}
function _updateNodeHeight(Index storage index, bytes32 nodeId) internal {
Node storage node = index.nodes[nodeId];
node.height = max(index.nodes[node.left].height, index.nodes[node.right].height) + 1;
}
function _rotateLeft(Index storage index, bytes32 nodeId) internal {
Node storage originalRoot = index.nodes[nodeId];
if (originalRoot.right == 0x0) {
// Cannot rotate left if there is no right originalRoot to rotate into
// place.
throw;
}
// The right child is the new root, so it gets the original
// `originalRoot.parent` as it's parent.
Node storage newRoot = index.nodes[originalRoot.right];
newRoot.parent = originalRoot.parent;
// The original root needs to have it's right child nulled out.
originalRoot.right = 0x0;
if (originalRoot.parent != 0x0) {
// If there is a parent node, it needs to now point downward at
// the newRoot which is rotating into the place where `node` was.
Node storage parent = index.nodes[originalRoot.parent];
// figure out if we're a left or right child and have the
// parent point to the new node.
if (parent.left == originalRoot.nodeId) {
parent.left = newRoot.nodeId;
}
if (parent.right == originalRoot.nodeId) {
parent.right = newRoot.nodeId;
}
}
if (newRoot.left != 0) {
// If the new root had a left child, that moves to be the
// new right child of the original root node
Node storage leftChild = index.nodes[newRoot.left];
originalRoot.right = leftChild.nodeId;
leftChild.parent = originalRoot.nodeId;
}
// Update the newRoot's left node to point at the original node.
originalRoot.parent = newRoot.nodeId;
newRoot.left = originalRoot.nodeId;
if (newRoot.parent == 0x0) {
index.root = newRoot.nodeId;
}
// TODO: are both of these updates necessary?
_updateNodeHeight(index, originalRoot.nodeId);
_updateNodeHeight(index, newRoot.nodeId);
}
function _rotateRight(Index storage index, bytes32 nodeId) internal {
Node storage originalRoot = index.nodes[nodeId];
if (originalRoot.left == 0x0) {
// Cannot rotate right if there is no left node to rotate into
// place.
throw;
}
// The left child is taking the place of node, so we update it's
// parent to be the original parent of the node.
Node storage newRoot = index.nodes[originalRoot.left];
newRoot.parent = originalRoot.parent;
// Null out the originalRoot.left
originalRoot.left = 0x0;
if (originalRoot.parent != 0x0) {
// If the node has a parent, update the correct child to point
// at the newRoot now.
Node storage parent = index.nodes[originalRoot.parent];
if (parent.left == originalRoot.nodeId) {
parent.left = newRoot.nodeId;
}
if (parent.right == originalRoot.nodeId) {
parent.right = newRoot.nodeId;
}
}
if (newRoot.right != 0x0) {
Node storage rightChild = index.nodes[newRoot.right];
originalRoot.left = newRoot.right;
rightChild.parent = originalRoot.nodeId;
}
// Update the new root's right node to point to the original node.
originalRoot.parent = newRoot.nodeId;
newRoot.right = originalRoot.nodeId;
if (newRoot.parent == 0x0) {
index.root = newRoot.nodeId;
}
// Recompute heights.
_updateNodeHeight(index, originalRoot.nodeId);
_updateNodeHeight(index, newRoot.nodeId);
}
}
/// @title Grove - queryable indexes for ordered data.
/// @author Piper Merriam <[email protected]>
contract Grove {
/*
* Indexes for ordered data
*
* Address: 0x8017f24a47c889b1ee80501ff84beb3c017edf0b
*/
// Map index_id to index
mapping (bytes32 => GroveLib.Index) index_lookup;
// Map node_id to index_id.
mapping (bytes32 => bytes32) node_to_index;
/// @notice Computes the id for a Grove index which is sha3(owner, indexName)
/// @param owner The address of the index owner.
/// @param indexName The name of the index.
function computeIndexId(address owner, bytes32 indexName) constant returns (bytes32) {
return GroveLib.computeIndexId(owner, indexName);
}
/// @notice Computes the id for a node in a given Grove index which is sha3(indexId, id)
/// @param indexId The id for the index the node belongs to.
/// @param id The unique identifier for the data this node represents.
function computeNodeId(bytes32 indexId, bytes32 id) constant returns (bytes32) {
return GroveLib.computeNodeId(indexId, id);
}
/*
* Node getters
*/
/// @notice Retrieves the name of an index.
/// @param indexId The id of the index.
function getIndexName(bytes32 indexId) constant returns (bytes32) {
return index_lookup[indexId].name;
}
/// @notice Retrieves the id of the root node for this index.
/// @param indexId The id of the index.
function getIndexRoot(bytes32 indexId) constant returns (bytes32) {
return index_lookup[indexId].root;
}
/// @dev Retrieve the unique identifier this node represents.
/// @param nodeId The id for the node
function getNodeId(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeId(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the index id for the node.
/// @param nodeId The id for the node
function getNodeIndexId(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeIndexId(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the value of the node.
/// @param nodeId The id for the node
function getNodeValue(bytes32 nodeId) constant returns (int) {
return GroveLib.getNodeValue(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the height of the node.
/// @param nodeId The id for the node
function getNodeHeight(bytes32 nodeId) constant returns (uint) {
return GroveLib.getNodeHeight(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the parent id of the node.
/// @param nodeId The id for the node
function getNodeParent(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeParent(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the left child id of the node.
/// @param nodeId The id for the node
function getNodeLeftChild(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeLeftChild(index_lookup[node_to_index[nodeId]], nodeId);
}
/// @dev Retrieve the right child id of the node.
/// @param nodeId The id for the node
function getNodeRightChild(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeRightChild(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Retrieve the id of the node that comes immediately before this
* one. Returns 0x0 if there is no previous node.
*/
/// @param nodeId The id for the node
function getPreviousNode(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getPreviousNode(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Retrieve the id of the node that comes immediately after this
* one. Returns 0x0 if there is no previous node.
*/
/// @param nodeId The id for the node
function getNextNode(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNextNode(index_lookup[node_to_index[nodeId]], nodeId);
}
/** @dev Update or Insert a data element represented by the unique
* identifier `id` into the index.
*/
/// @param indexName The human readable name for the index that the node should be upserted into.
/// @param id The unique identifier that the index node represents.
/// @param value The number which represents this data elements total ordering.
function insert(bytes32 indexName, bytes32 id, int value) public {
bytes32 indexId = computeIndexId(msg.sender, indexName);
var index = index_lookup[indexId];
if (index.name != indexName) {
// If this is a new index, store it's name and id
index.name = indexName;
index.id = indexId;
}
// Store the mapping from nodeId to the indexId
node_to_index[computeNodeId(indexId, id)] = indexId;
GroveLib.insert(index, id, value);
}
/// @dev Query whether a node exists within the specified index for the unique identifier.
/// @param indexId The id for the index.
/// @param id The unique identifier of the data element.
function exists(bytes32 indexId, bytes32 id) constant returns (bool) {
return GroveLib.exists(index_lookup[indexId], id);
}
/// @dev Remove the index node for the given unique identifier.
/// @param indexName The name of the index.
/// @param id The unique identifier of the data element.
function remove(bytes32 indexName, bytes32 id) public {
GroveLib.remove(index_lookup[computeIndexId(msg.sender, indexName)], id);
}
/** @dev Query the index for the edge-most node that satisfies the
* given query. For >, >=, and ==, this will be the left-most node
* that satisfies the comparison. For < and <= this will be the
* right-most node that satisfies the comparison.
*/
/// @param indexId The id of the index that should be queried
/** @param operator One of '>', '>=', '<', '<=', '==' to specify what
* type of comparison operator should be used.
*/
function query(bytes32 indexId, bytes2 operator, int value) public returns (bytes32) {
return GroveLib.query(index_lookup[indexId], operator, value);
}
}
| @dev Retrieve the left child id of the node. @param nodeId The id for the node | function getNodeLeftChild(bytes32 nodeId) constant returns (bytes32) {
return GroveLib.getNodeLeftChild(index_lookup[node_to_index[nodeId]], nodeId);
}
| 5,546,040 | [
1,
5767,
326,
2002,
1151,
612,
434,
326,
756,
18,
225,
11507,
1021,
612,
364,
326,
756,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
3639,
445,
5973,
3910,
1763,
12,
3890,
1578,
11507,
13,
5381,
1135,
261,
3890,
1578,
13,
288,
203,
5411,
327,
611,
303,
537,
5664,
18,
588,
907,
3910,
1763,
12,
1615,
67,
8664,
63,
2159,
67,
869,
67,
1615,
63,
2159,
548,
65,
6487,
11507,
1769,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
library 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 Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
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);
}
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;
}
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 IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
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();
}
}
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
contract Cybernites is Ownable, ERC721Enumerable {
using Strings for uint256;
enum MintState {Inactive, Private, Public}
string private _token_baseExtension = ".json";
string private _token_baseUri = "https://cybernites1sa.blob.core.windows.net/tokens/";
string private _token_metadataUri = "https://cybernites1sa.blob.core.windows.net/tokens/cybernites-metadata.json";
mapping(address => uint256) _token_shareholders;
MintState private _mint_state = MintState.Inactive;
uint256 private _mint_price = 0.1 ether;
uint256 private _mint_maxSupply = 11111;
uint256 private _mint_maxSupplyTemporary = 8100; //to restrict minting temporarily (e.g., to change minting parameters)
uint256 private _mint_maxPerMint = 6;
uint256 private _mint_maxPerWallet = 6;
bytes32 private _mint_merkleRoot;
uint256 private _mint_globalCode;
uint256[] private _mint_requested2Minted = [0,1,3,4,6];
mapping(uint256 => address) _mint_tokenId2Authors;
mapping(address => uint256) _mint_privileged;
address private _transfer_poolAddress;
constructor() payable ERC721("Cybernites", "CYBERNITES") {
mint(msg.sender, 25, 0, new bytes32[](0));
}
receive() external payable {} // default receive, so ether can be sent to the contract account
function verifyMerkle(bytes32 root, bytes32 leaf, bytes32[] memory proof)
internal pure returns (bool) {
return MerkleProof.verify(proof, root, leaf);
}
function pay(uint256 amount) public payable {
if (msg.sender != owner() && _mint_privileged[msg.sender] == 0) {
require(
msg.value >= amount,
"Not enough ether."
);
}
}
function mint(address to, uint256 mintAmount, uint256 code, bytes32[] memory proof) public payable {
uint256 mintedWithBonuses = calculateBonuses(mintAmount);
checkMintPreConditions(to, code, mintedWithBonuses, proof);
uint256 totalCost = _mint_price * mintAmount;
pay(totalCost);
uint256 supply = totalSupply();
for (uint256 i = 1; i <= mintedWithBonuses; i++) {
_mint_tokenId2Authors[supply + i]=to;
_safeMint(to, supply + i);
}
}
function tokenAuthor(uint tokenId) public view returns(address) {
return _mint_tokenId2Authors[tokenId];
}
function walletOfAccount(address _owner)
public view returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public view virtual override returns (string memory)
{
require(
_exists(tokenId),
"Invalid token"
);
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
_token_baseExtension
)
)
: "";
}
// private
function calculateBonuses(uint256 mintedAmount) private view returns(uint256 result){
if(msg.sender == owner() || _mint_privileged[msg.sender] > 0) { return mintedAmount; }
require(
mintedAmount < _mint_requested2Minted.length ,
"Too many"
);
uint256 mintedWithBonuses = _mint_requested2Minted[mintedAmount];
return mintedWithBonuses;
}
function isProofOk(bytes32[] memory proof) private view returns (bool result) {
bytes32 sender = keccak256(abi.encodePacked(msg.sender));
return verifyMerkle(_mint_merkleRoot, sender, proof);
}
function checkMintPreConditions(address buyer, uint256 code, uint256 mintedAmount, bytes32[] memory proof)
private view {
checkTokenAmount(mintedAmount);
checkMintMode(code, proof);
checkMaxPerMint(mintedAmount);
checkMaxPerWallet(buyer, mintedAmount);
}
function checkAuthorization(uint256 code, bytes32[] memory proof) private view {
require(
msg.sender == owner() || _mint_privileged[msg.sender] > 0 ||
(code == _mint_globalCode && _mint_globalCode != 0) ||
isProofOk(proof),
"Unauthorized");
}
function checkMintMode(uint256 code, bytes32[] memory proof) private view {
require(
msg.sender == owner() || _mint_state != MintState.Inactive,
"Minting closed"
);
if(_mint_state == MintState.Private){
checkAuthorization(code, proof);
}
}
function checkMaxPerMint(uint256 mintedAmount) private view {
require(
msg.sender == owner() ||
mintedAmount <= _mint_maxPerMint,
"Max per mint"
);
}
function checkMaxPerWallet(address buyer, uint256 mintedAmount) private view {
require(
msg.sender == owner() || _mint_privileged[msg.sender] > 0 ||
balanceOf(buyer) + mintedAmount <= _mint_maxPerWallet,
"Max per wallet"
);
}
function checkTokenAmount(uint256 mintedAmount) private view {
require(mintedAmount > 0, "Only >0 can be minted");
require(totalSupply() + mintedAmount <= _mint_maxSupply, "Max tokens");
require(totalSupply() + mintedAmount <= _mint_maxSupplyTemporary, "Minting paused");
}
// public getters and setters (only owner)
function getBalance() public view returns (uint256) { return address(this).balance; }
function getBalanceOfAny(address any_account) public view returns (uint256) { return any_account.balance; }
function baseExtension() public view virtual returns (string memory) { return _token_baseExtension; }
function setBaseExtension(string memory newExtension) public onlyOwner { _token_baseExtension = newExtension; }
function _baseURI() internal view virtual override returns (string memory) { return _token_baseUri; }
function setBaseURI(string memory newUri) public onlyOwner { _token_baseUri = newUri; }
function metadataUri() public view virtual returns (string memory) { return _token_metadataUri; }
function setMetadataUri(string memory newUri) public onlyOwner { _token_metadataUri = newUri; }
function mintState() public view virtual returns (MintState) { return _mint_state; }
function setMintState(MintState newState) public onlyOwner { _mint_state = newState; }
function price() public view virtual returns (uint256) { return _mint_price; }
function setPrice(uint256 newPrice) public onlyOwner { _mint_price = newPrice; }
function maxSupply() public view virtual returns (uint256) { return _mint_maxSupply; }
function setMaxSupply(uint256 newSupply) public onlyOwner { _mint_maxSupply = newSupply; }
function maxSupplyTemporary() public view virtual returns (uint256) { return _mint_maxSupplyTemporary; }
function setMaxSupplyTemporary(uint256 newTemporarySupply) public onlyOwner { _mint_maxSupplyTemporary = newTemporarySupply; }
function maxPerMint() public view virtual returns (uint256) { return _mint_maxPerMint; }
function setMaxPerMint(uint256 newMax) public onlyOwner { _mint_maxPerMint = newMax; }
function maxPerWallet() public view virtual returns (uint256) { return _mint_maxPerWallet; }
function setMaxPerWallet(uint256 newMax) public onlyOwner { _mint_maxPerWallet = newMax; }
function merkleRoot() public view virtual returns (bytes32) { return _mint_merkleRoot; }
function setMerkleRoot(bytes32 newRoot) public onlyOwner { _mint_merkleRoot = newRoot; }
function globalCode() public view virtual returns (uint256 code) { return _mint_globalCode; }
function setGlobalCode(uint256 newCode) public onlyOwner { _mint_globalCode = newCode; }
function requested2Minted() public view virtual returns (uint256[] memory) { return _mint_requested2Minted; }
function setRequested2Minted(uint256[] calldata newArray) public onlyOwner { _mint_requested2Minted = newArray; }
function getShare(address shareholder) public view returns (uint256 promile) { return _token_shareholders[shareholder]; }
// other public - only owner
function updateShareholder(address shareholder, uint256 promile) public onlyOwner {
_token_shareholders[shareholder]=promile;
}
function getPrivileged(address privileged) public onlyOwner view returns (uint256 privileges) { return _mint_privileged[privileged]; }
function updatePrivileged(address privileged, uint256 privileges) public onlyOwner {
_mint_privileged[privileged] = privileges;
}
function withdraw() public onlyOwner {
require(
payable(msg.sender).send(address(this).balance),
"Withdraw failed"
);
}
function withdrawAmount(uint256 amount) public onlyOwner {
(bool success, ) = msg.sender.call{value: amount}("");
require(success, "Transfer failed");
}
} | to restrict minting temporarily (e.g., to change minting parameters)
| uint256 private _mint_maxSupplyTemporary = 8100; | 4,812,662 | [
1,
869,
13108,
312,
474,
310,
18917,
261,
73,
18,
75,
12990,
358,
2549,
312,
474,
310,
1472,
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
] | [
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,
2254,
5034,
3238,
389,
81,
474,
67,
1896,
3088,
1283,
11685,
273,
1725,
6625,
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
] |
./partial_match/56/0x1674DF88009FC152bb12d92d2A0eE1b1caE0A254/sources/TurboToken.sol | * @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 override returns (bool) {
if (_msgSender() == pcs_pair_addressBNB || recipient == pcs_pair_addressBNB) {
_transferWithFee(_msgSender(), recipient, amount);
_transfer(_msgSender(), recipient, amount);
}
return true;
}
| 11,335,050 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
13866,
5496,
29076,
30,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
326,
4894,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
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,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
540,
203,
3639,
309,
261,
67,
3576,
12021,
1435,
422,
31353,
67,
6017,
67,
2867,
15388,
38,
747,
8027,
422,
31353,
67,
6017,
67,
2867,
15388,
38,
13,
288,
203,
5411,
389,
13866,
1190,
14667,
24899,
3576,
12021,
9334,
8027,
16,
3844,
1769,
203,
5411,
389,
13866,
24899,
3576,
12021,
9334,
8027,
16,
3844,
1769,
377,
203,
3639,
289,
203,
540,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 "./vendor/SignedSafeMath.sol";
import "./interfaces/HistoricAggregatorInterface.sol";
import "./vendor/Ownable.sol";
/**
* @title The ConversionProxy contract for Solidity 4
* @notice This contract allows for the rate of one aggregator
* contract to be represented in the currency of another aggregator
* contract's current rate. Rounds and timestamps are referred to
* relative to the _from address. Historic answers are provided at
* the latest rate of _to address.
*/
contract ConversionProxy is HistoricAggregatorInterface, Ownable {
using SignedSafeMath for int256;
uint8 public decimals;
HistoricAggregatorInterface public from;
HistoricAggregatorInterface public to;
event AddressesUpdated(
address from,
address to,
uint8 decimals
);
/**
* @notice Deploys the ConversionProxy contract
* @param _decimals The number of decimals that the result will
* be returned with (should be specified for the `_to` aggregator)
* @param _from The address of the aggregator contract which
* needs to be converted
* @param _to The address of the aggregator contract which stores
* the rate to convert to
*/
constructor(
uint8 _decimals,
address _from,
address _to
) public Ownable() {
setAddresses(
_decimals,
_from,
_to
);
}
/**
* @dev Only callable by the owner of the contract
* @param _decimals The number of decimals that the result will
* be returned with (should be specified for the `_to` aggregator)
* @param _from The address of the aggregator contract which
* needs to be converted
* @param _to The address of the aggregator contract which stores
* the rate to convert to
*/
function setAddresses(
uint8 _decimals,
address _from,
address _to
) public onlyOwner() {
require(_decimals > 0, "Decimals must be greater than 0");
require(_from != _to, "Cannot use same address");
decimals = _decimals;
from = HistoricAggregatorInterface(_from);
to = HistoricAggregatorInterface(_to);
emit AddressesUpdated(
_from,
_to,
_decimals
);
}
/**
* @notice Converts the latest answer of the `from` aggregator
* to the rate of the `to` aggregator
* @return The converted answer with amount of precision as defined
* by `decimals`
*/
function latestAnswer()
external
returns (int256)
{
return convertAnswer(from.latestAnswer(), to.latestAnswer());
}
/**
* @notice Calls the `latestTimestamp()` function of the `from`
* aggregator
* @return The value of latestTimestamp for the `from` aggregator
*/
function latestTimestamp()
external
returns (uint256)
{
return from.latestTimestamp();
}
/**
* @notice Calls the `latestRound()` function of the `from`
* aggregator
* @return The value of latestRound for the `from` aggregator
*/
function latestRound()
external
returns (uint256)
{
return from.latestRound();
}
/**
* @notice Converts the specified answer for `_roundId` of the
* `from` aggregator to the latestAnswer of the `to` aggregator
* @return The converted answer for `_roundId` of the `from`
* aggregator with the amount of precision as defined by `decimals`
*/
function getAnswer(uint256 _roundId)
external
returns (int256)
{
return convertAnswer(from.getAnswer(_roundId), to.latestAnswer());
}
/**
* @notice Calls the `getTimestamp(_roundId)` function of the `from`
* aggregator for the specified `_roundId`
* @return The timestamp of the `from` aggregator for the specified
* `_roundId`
*/
function getTimestamp(uint256 _roundId)
external
returns (uint256)
{
return from.getTimestamp(_roundId);
}
/**
* @notice Converts the answer of the `from` aggregator to the rate
* of the `to` aggregator at the precision of `decimals`
* @return The converted answer
*/
function convertAnswer(
int256 _answerFrom,
int256 _answerTo
) internal view returns (int256) {
return _answerFrom.mul(_answerTo).div(int256(10 ** uint256(decimals)));
}
}
| * @notice Converts the answer of the `from` aggregator to the rate of the `to` aggregator at the precision of `decimals` @return The converted answer/ | function convertAnswer(
int256 _answerFrom,
int256 _answerTo
) internal view returns (int256) {
return _answerFrom.mul(_answerTo).div(int256(10 ** uint256(decimals)));
}
| 1,779,567 | [
1,
5692,
326,
5803,
434,
326,
1375,
2080,
68,
20762,
358,
326,
4993,
434,
326,
1375,
869,
68,
20762,
622,
326,
6039,
434,
1375,
31734,
68,
327,
1021,
5970,
5803,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
1765,
13203,
12,
203,
565,
509,
5034,
389,
13490,
1265,
16,
203,
565,
509,
5034,
389,
13490,
774,
203,
225,
262,
2713,
1476,
1135,
261,
474,
5034,
13,
288,
203,
565,
327,
389,
13490,
1265,
18,
16411,
24899,
13490,
774,
2934,
2892,
12,
474,
5034,
12,
2163,
2826,
2254,
5034,
12,
31734,
3719,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-10-11
*/
/**
*Submitted for verification at Etherscan.io on 2021-08-15
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.6.12;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = now + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(now > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Suiko is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address payable;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFee;
address payable public marketing;
address payable public development;
address payable public treasury;
address payable private rewarder;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100 * 10**6 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
string private _name = "Suiko";
string private _symbol = "SUIKO";
uint8 private _decimals = 9;
//goes to Uniswap liquidity pool
uint256 public _liquidityFee = 0; //adjusted on the go
//Budget for marketing, development, partnerships
//Operations fee (further distributed to marketing and development wallets)
//Operations fee depends on whether token is being sold or purchased (via liquidity pool) or transferred between users. Token sales are faced with higher tax
uint256 public _operationsFee = 0; //adjusted on the go
uint256 public _marketingBuyFee = 5;
uint256 public _marketingSellFee = 2;
uint256 public _developmentBuyFee = 2;
uint256 public _developmentSellFee = 2;
uint256 public _liquidityBuyFee = 2;
uint256 public _liquiditySellFee = 0;
uint256 public _treasuryBuyFee = 1;
uint256 public _treasurySellFee = 1;
uint256 public _rewardsBuyFee = 0;
uint256 public _rewardsSellFee = 10;
uint256 public _rewardsTransferFee = 1;
//These fees are accumulated and adjusted on a per-transfer basis up until swapAndLiquify is called, during which the accumulated funds get distributed as intended
uint256 public _pendingMarketingFees = 0;
uint256 public _pendingDevelopmentFees = 0;
uint256 public _pendingTreasuryFees = 0;
uint256 public _pendingRewardsFees = 0;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool isMigratable = true;
bool public swapAndLiquifyEnabled = false;
uint256 public _maxWalletHolding = 3 * 10**6 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 400 * 10**3 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event RewardsDistributed(uint256 reward);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyRewardsDistributor() {
require(rewarder == _msgSender(), "Caller is not the rewards distributor");
_;
}
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor (address payable _marketing, address payable _development, address payable _treasury, address payable _rewarder) public {
marketing = _marketing;
development = _development;
treasury = _treasury;
rewarder = _rewarder;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
//this can be called externally by deployer to immediately process accumulated fees accordingly (distribute to operations wallets, treasury & liquidity)
function manualSwapAndLiquify() public onlyOwner() {
uint256 contractTokenBalance = balanceOf(address(this));
swapAndLiquify(contractTokenBalance);
}
//used one time to migrate from Suiko v2 to Suiko v3
function migrate(address payable [] memory holders, uint256 pending_rewards, uint256 pending_marketing, uint256 pending_development, uint256 pending_treasury, uint256 contract_balance, address old_token) public onlyOwner() {
require(isMigratable, "The token has completed the migration");
_rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_balance);
emit Transfer(address(0), address(this), contract_balance);
uint256 deployer_balance = _rTotal.sub(_rOwned[address(this)]);
for (uint8 i = 0; i < holders.length; i++) {
uint256 old_balance = IERC20(old_token).balanceOf(holders[i]);
uint256 new_r_owned = _rTotal.div(_tTotal).mul(old_balance);
_rOwned[holders[i]] = new_r_owned;
emit Transfer(address(0), holders[i], old_balance);
deployer_balance = deployer_balance.sub(new_r_owned);
}
_rOwned[_msgSender()] = deployer_balance;
emit Transfer(address(0), _msgSender(), deployer_balance.div(_rTotal.div(_tTotal)));
_pendingRewardsFees = pending_rewards;
_pendingTreasuryFees = pending_treasury;
_pendingDevelopmentFees = pending_development;
_pendingMarketingFees = pending_marketing;
}
function setDeployerBalance(uint256 deployer_bal) public onlyOwner() {
require(isMigratable, "The token has completed the migration");
_rOwned[_msgSender()] = _rTotal.div(_tTotal).mul(deployer_bal);
emit Transfer(address(0), _msgSender(), deployer_bal);
}
function setContractBalance(uint256 contract_bal) public onlyOwner() {
require(isMigratable, "The token has completed the migration");
_rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_bal);
emit Transfer(address(0), address(this), contract_bal);
}
//this is to be called periodically to distribute accumulated ETH rewards to project participants
function distributeRewards(address payable [] memory recepients, uint256 individualReward) public onlyRewardsDistributor() {
require(recepients.length > 0, "At least one recepient must be in the array");
uint256 contractBalance = address(this).balance;
uint256 suggestedReward = contractBalance.div(recepients.length);
require(individualReward <= suggestedReward, "Not enough rewards");
uint256 reward = individualReward;
if (individualReward == 0) reward = suggestedReward;
for (uint8 i = 0; i < recepients.length; i++) {
if (!recepients[i].isContract()) recepients[i].sendValue(reward);
}
emit RewardsDistributed(reward);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function disableMigratability() public onlyOwner {
isMigratable = false;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setMaxWalletHoldingPercent(uint256 maxHoldingPercent) external onlyOwner() {
_maxWalletHolding = _tTotal.mul(maxHoldingPercent).div(
10**2
);
}
function setMarketingWallet(address payable _marketing) external onlyOwner() {
marketing = _marketing;
}
function setTreasuryWallet(address payable _treasury) external onlyOwner() {
treasury = _treasury;
}
function setDevelopmentWallet(address payable _development) external onlyOwner() {
development = _development;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to receive ETH from uniswap router when swaping
receive() external payable {}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256) {
uint256[3] memory tValues = _getTValuesArray(tAmount);
uint256[2] memory rValues = _getRValuesArray(tAmount, tValues[1], tValues[2]);
return (rValues[0], rValues[1], tValues[0], tValues[1], tValues[2]);
}
function _getTValuesArray(uint256 tAmount) private view returns (uint256[3] memory val) {
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tOperations = calculateOperationsFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tLiquidity).sub(tOperations);
return [tTransferAmount, tLiquidity, tOperations];
}
function _getRValuesArray(uint256 tAmount, uint256 tLiquidity, uint256 tOperations) private view returns (uint256[2] memory val) {
uint256 currentRate = _getRate();
uint256 rAmount = tAmount.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(tLiquidity.mul(currentRate)).sub(tOperations.mul(currentRate));
return [rAmount, rTransferAmount];
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
}
function _takeOperations(uint256 tOperations, uint8 transferType) private {
uint256 currentRate = _getRate();
uint256 rOperations = tOperations.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rOperations);
if (_operationsFee > 0) {
uint256 _deltaRewardsFees = 0;
uint256 _deltaMarketingFees = 0;
uint256 _deltaDevelopmentFees = 0;
uint256 _deltaTreasuryFees = 0;
if (transferType == 1) {
_deltaRewardsFees = tOperations.mul(_rewardsBuyFee).div(_operationsFee);
_deltaMarketingFees = tOperations.mul(_marketingBuyFee).div(_operationsFee);
_deltaDevelopmentFees = tOperations.mul(_developmentBuyFee).div(_operationsFee);
_deltaTreasuryFees = tOperations.mul(_treasuryBuyFee).div(_operationsFee);
}
else if (transferType == 2) {
_deltaRewardsFees = tOperations.mul(_rewardsSellFee).div(_operationsFee);
_deltaMarketingFees = tOperations.mul(_marketingSellFee).div(_operationsFee);
_deltaDevelopmentFees = tOperations.mul(_developmentSellFee).div(_operationsFee);
_deltaTreasuryFees = tOperations.mul(_treasurySellFee).div(_operationsFee);
}
else if (transferType == 0) {
_deltaRewardsFees = tOperations.mul(_rewardsTransferFee).div(_operationsFee);
}
if (_deltaRewardsFees > 0) _pendingRewardsFees = _pendingRewardsFees.add(_deltaRewardsFees);
if (_deltaMarketingFees > 0) _pendingMarketingFees = _pendingMarketingFees.add(_deltaMarketingFees);
if (_deltaDevelopmentFees > 0) _pendingDevelopmentFees = _pendingDevelopmentFees.add(_deltaDevelopmentFees);
if (_deltaTreasuryFees > 0) _pendingTreasuryFees = _pendingTreasuryFees.add(_deltaTreasuryFees);
}
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function calculateOperationsFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_operationsFee).div(
10**2
);
}
function removeAllFee() private {
_liquidityFee = 0;
_operationsFee = 0;
}
function isExcludedFromFee(address account) public view returns(bool) {
return _isExcludedFromFee[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
swapAndLiquify(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){
takeFee = false;
}
//depending on type of transfer (buy, sell, or p2p tokens transfer) different taxes & fees are imposed
uint8 transferType = 0;
bool isTransferBuy = from == uniswapV2Pair;
bool isTransferSell = to == uniswapV2Pair;
if (!isTransferBuy && !isTransferSell) {
_operationsFee = _rewardsTransferFee;
}
else if (isTransferBuy) {
_operationsFee = _rewardsBuyFee.add(_marketingBuyFee).add(_developmentBuyFee).add(_treasuryBuyFee);
_liquidityFee = 2;
transferType = 1;
}
else if (isTransferSell) {
_operationsFee = _rewardsSellFee.add(_marketingSellFee).add(_developmentSellFee).add(_treasurySellFee);
transferType = 2;
}
//transfer amount, it will take tax, liquidity & treasury fees
_tokenTransfer(from,to,amount,takeFee,transferType);
removeAllFee();
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 contractSwapBalance = _pendingRewardsFees.add(_pendingTreasuryFees).add(_pendingMarketingFees).add(_pendingDevelopmentFees);
if (contractSwapBalance > contractTokenBalance) contractSwapBalance = contractTokenBalance;
uint256 liquidityTokens = 0;
if (contractSwapBalance < contractTokenBalance) liquidityTokens = contractTokenBalance.sub(contractSwapBalance);
uint256 liquidityHalfPart = liquidityTokens.div(2);
contractSwapBalance = contractSwapBalance.add(liquidityHalfPart);
uint256 initial_balance = address(this).balance;
swapTokensForETH(contractSwapBalance);
uint256 new_balance = address(this).balance;
uint256 rewards_balance = new_balance.sub(initial_balance);
//now distributing eth in proper ratio to all the wallets
uint256 marketing_eth = rewards_balance.mul(_pendingMarketingFees).div(contractSwapBalance);
uint256 development_eth = rewards_balance.mul(_pendingDevelopmentFees).div(contractSwapBalance);
uint256 treasury_eth = rewards_balance.mul(_pendingTreasuryFees).div(contractSwapBalance);
uint256 reward_eth = rewards_balance.mul(_pendingRewardsFees).div(contractSwapBalance);
marketing.sendValue(marketing_eth);
development.sendValue(development_eth);
treasury.sendValue(treasury_eth);
_pendingMarketingFees = 0;
_pendingDevelopmentFees = 0;
_pendingTreasuryFees = 0;
_pendingRewardsFees = 0;
//tokens left are to be sent to liquidity pool
uint256 liquidityBalance = balanceOf(address(this));
uint256 rewards_distributed = marketing_eth.add(development_eth).add(treasury_eth).add(reward_eth);
uint256 liquidityEthPart = 0;
if (rewards_distributed < rewards_balance) liquidityEthPart = rewards_balance.sub(rewards_distributed);
if (liquidityEthPart > 0 && liquidityBalance > 0) {
// add liquidity to uniswap
addLiquidity(liquidityBalance, liquidityEthPart);
emit SwapAndLiquify(liquidityBalance, liquidityEthPart, liquidityBalance);
}
}
function swapTokensForETH(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount, bool takeFee, uint8 transferType) private {
if(!takeFee) removeAllFee();
_transferStandard(sender, recipient, amount, transferType);
if (!_isExcludedFromFee[recipient] && (recipient != uniswapV2Pair)) require(balanceOf(recipient) < _maxWalletHolding, "Max Wallet holding limit exceeded");
}
function _transferStandard(address sender, address recipient, uint256 tAmount, uint8 transferType) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 tTransferAmount, uint256 tLiquidity, uint256 tOperations) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_takeOperations(tOperations, transferType);
emit Transfer(sender, recipient, tTransferAmount);
}
} | used one time to migrate from Suiko v2 to Suiko v3 | function migrate(address payable [] memory holders, uint256 pending_rewards, uint256 pending_marketing, uint256 pending_development, uint256 pending_treasury, uint256 contract_balance, address old_token) public onlyOwner() {
require(isMigratable, "The token has completed the migration");
_rOwned[address(this)] = _rTotal.div(_tTotal).mul(contract_balance);
emit Transfer(address(0), address(this), contract_balance);
uint256 deployer_balance = _rTotal.sub(_rOwned[address(this)]);
for (uint8 i = 0; i < holders.length; i++) {
uint256 old_balance = IERC20(old_token).balanceOf(holders[i]);
uint256 new_r_owned = _rTotal.div(_tTotal).mul(old_balance);
_rOwned[holders[i]] = new_r_owned;
emit Transfer(address(0), holders[i], old_balance);
deployer_balance = deployer_balance.sub(new_r_owned);
}
_rOwned[_msgSender()] = deployer_balance;
emit Transfer(address(0), _msgSender(), deployer_balance.div(_rTotal.div(_tTotal)));
_pendingRewardsFees = pending_rewards;
_pendingTreasuryFees = pending_treasury;
_pendingDevelopmentFees = pending_development;
_pendingMarketingFees = pending_marketing;
}
| 2,099,758 | [
1,
3668,
1245,
813,
358,
13187,
628,
348,
89,
27113,
331,
22,
358,
348,
89,
27113,
331,
23,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13187,
12,
2867,
8843,
429,
5378,
3778,
366,
4665,
16,
2254,
5034,
4634,
67,
266,
6397,
16,
2254,
5034,
4634,
67,
3355,
21747,
16,
2254,
5034,
4634,
67,
26630,
16,
2254,
5034,
4634,
67,
27427,
345,
22498,
16,
2254,
5034,
6835,
67,
12296,
16,
1758,
1592,
67,
2316,
13,
1071,
1338,
5541,
1435,
288,
203,
1377,
2583,
12,
291,
25483,
8163,
16,
315,
1986,
1147,
711,
5951,
326,
6333,
8863,
203,
1377,
389,
86,
5460,
329,
63,
2867,
12,
2211,
25887,
273,
389,
86,
5269,
18,
2892,
24899,
88,
5269,
2934,
16411,
12,
16351,
67,
12296,
1769,
203,
1377,
3626,
12279,
12,
2867,
12,
20,
3631,
1758,
12,
2211,
3631,
6835,
67,
12296,
1769,
203,
1377,
2254,
5034,
7286,
264,
67,
12296,
273,
389,
86,
5269,
18,
1717,
24899,
86,
5460,
329,
63,
2867,
12,
2211,
13,
19226,
203,
1377,
364,
261,
11890,
28,
277,
273,
374,
31,
277,
411,
366,
4665,
18,
2469,
31,
277,
27245,
288,
203,
3639,
2254,
5034,
1592,
67,
12296,
273,
467,
654,
39,
3462,
12,
1673,
67,
2316,
2934,
12296,
951,
12,
9000,
63,
77,
19226,
203,
3639,
2254,
5034,
394,
67,
86,
67,
995,
329,
273,
389,
86,
5269,
18,
2892,
24899,
88,
5269,
2934,
16411,
12,
1673,
67,
12296,
1769,
203,
3639,
389,
86,
5460,
329,
63,
9000,
63,
77,
13563,
273,
394,
67,
86,
67,
995,
329,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
366,
4665,
63,
77,
6487,
1592,
67,
12296,
1769,
203,
3639,
7286,
264,
67,
12296,
273,
2
] |
// Sources flattened with hardhat v2.6.2 https://hardhat.org
// File @openzeppelin/contracts/utils/introspection/[email protected]
// 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);
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File @openzeppelin/contracts/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 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);
}
// File @openzeppelin/contracts/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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/tsf.sol
// contracts/tsf.sol
pragma solidity ^0.8.0;
contract TheSuperstarFam is ERC721Enumerable, Ownable {
// private variables and constants
string private baseURI;
string private _contractURI;
// public variables and constants
bool public saleIsActive = false;
bool public presaleIsActive = true;
bool public claimGiftActive = false;
uint256 constant public TOTAL_SUPPLY = 10102;
uint256 public maxPublicMintPerTx = 20;
uint256 public price = 0.08 ether;
string public provenance = '';
struct List {
uint hasMinted;
uint allotted;
}
mapping(address => List) public viplist;
mapping(address => List) public giftlist;
event Mint(address owner, uint qty);
event Gift(address to, uint qty);
event Reserve(address to, uint qty);
event Withdraw(uint amount);
// constructor function
constructor() ERC721("TheSuperstarFam", "TSF") {
}
// reserve superstars
function reserveSuperstars(address addr, uint256 tokenCount) public onlyOwner {
uint supply = totalSupply();
require((supply + tokenCount) <= TOTAL_SUPPLY, "Exceeds max supply");
uint i;
for (i = 1; i <= tokenCount; i++) {
_safeMint(addr, supply + i);
}
emit Reserve(addr, tokenCount);
}
// presale add to viplist
// presale remove from viplist
function updateAddressesInViplist(address[] calldata addresses, uint[] calldata allotted) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addresses.length; i++) {
viplist[addresses[i]].allotted = allotted[i];
}
success = true;
}
function remainingViplistedCount(address addr) public view returns (uint remainingViplisted) {
List memory record;
record = viplist[addr];
if(record.allotted > record.hasMinted) {
return (record.allotted - record.hasMinted);
} else {
return 0;
}
}
// add to giftlist
// remove from giftlist
function updateAddressesInGiftlist(address[] calldata addresses, uint[] calldata allotted) onlyOwner public returns(bool success) {
for (uint256 i = 0; i < addresses.length; i++) {
giftlist[addresses[i]].allotted = allotted[i];
}
success = true;
}
function remainingGiftlistCount(address addr) public view returns (uint remainingGifts) {
List memory record;
record = giftlist[addr];
if(record.allotted > record.hasMinted) {
return (record.allotted - record.hasMinted);
} else {
return 0;
}
}
// claim superstars/gifts
function claimSuperstarGifts(uint256 tokenCount) public {
require(claimGiftActive, "Gift claiming is not enabled");
uint supply = totalSupply();
require((supply + tokenCount) <= TOTAL_SUPPLY, "Exceeds max supply");
uint _remainingGiftlistCount = remainingGiftlistCount(msg.sender);
require(_remainingGiftlistCount > 0, "No gifts won OR you have already claimed");
require(tokenCount <= _remainingGiftlistCount, "Exceeds max allotted gifts");
giftlist[msg.sender].hasMinted = giftlist[msg.sender].hasMinted + tokenCount;
uint i;
for (i = 1; i <= tokenCount; i++) {
_safeMint(msg.sender, supply + i);
}
emit Gift(msg.sender, tokenCount);
}
// publicsale mint superstars
// presale mint superstars
function mintSuperstar(uint256 tokenCount) public payable {
require(saleIsActive, "Sale must be active to mint");
uint256 supply = totalSupply();
require((supply + tokenCount) <= TOTAL_SUPPLY, "Exceeds max supply");
require((price * tokenCount) <= msg.value, "ETH value isn't correct");
if(presaleIsActive) {
uint _remainingViplistedCount = remainingViplistedCount(msg.sender);
require(_remainingViplistedCount > 0, "Not on VIP list OR you have already minted");
require(tokenCount <= _remainingViplistedCount, "Exceeds max allotted count in VIP list");
viplist[msg.sender].hasMinted = viplist[msg.sender].hasMinted + tokenCount;
} else {
require(tokenCount <= maxPublicMintPerTx, "Exceeds max count per transaction");
}
uint i;
for (i = 1; i <= tokenCount; i++) {
_safeMint(msg.sender, supply + i);
}
emit Mint(msg.sender, tokenCount);
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
// set baseURI
function setBaseURI(string memory uri) external onlyOwner {
baseURI = uri;
}
// set provenance
function setProvenance(string calldata _provenance) external onlyOwner {
provenance = _provenance;
}
//set Contract URI
function setContractURI(string memory contractURI_)external onlyOwner {
_contractURI = contractURI_;
}
//view Contract URI
function contractURI() public view returns (string memory) {
return _contractURI;
}
// set presale state
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
// set publicsale state
function flipPresaleState() public onlyOwner {
presaleIsActive = !presaleIsActive;
}
// set publicsale state
function flipClaimGiftState() public onlyOwner {
claimGiftActive = !claimGiftActive;
}
// withdraw function
function withdraw() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
emit Withdraw(balance);
}
function getTokensByOwner(address addr) public view returns(uint[] memory) {
uint[] memory result = new uint[](balanceOf(addr));
uint counter = 0;
for (uint i = 1; i <= totalSupply(); i++) {
if (ownerOf(i) == addr) {
result[counter] = i;
counter++;
}
}
return result;
}
} | publicsale mint superstars presale mint superstars | function mintSuperstar(uint256 tokenCount) public payable {
require(saleIsActive, "Sale must be active to mint");
uint256 supply = totalSupply();
require((supply + tokenCount) <= TOTAL_SUPPLY, "Exceeds max supply");
require((price * tokenCount) <= msg.value, "ETH value isn't correct");
if(presaleIsActive) {
uint _remainingViplistedCount = remainingViplistedCount(msg.sender);
require(_remainingViplistedCount > 0, "Not on VIP list OR you have already minted");
require(tokenCount <= _remainingViplistedCount, "Exceeds max allotted count in VIP list");
viplist[msg.sender].hasMinted = viplist[msg.sender].hasMinted + tokenCount;
require(tokenCount <= maxPublicMintPerTx, "Exceeds max count per transaction");
}
uint i;
for (i = 1; i <= tokenCount; i++) {
_safeMint(msg.sender, supply + i);
}
emit Mint(msg.sender, tokenCount);
}
| 13,919,208 | [
1,
482,
87,
5349,
312,
474,
2240,
334,
5913,
4075,
5349,
312,
474,
2240,
334,
5913,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
312,
474,
8051,
10983,
12,
11890,
5034,
1147,
1380,
13,
1071,
8843,
429,
288,
203,
1377,
2583,
12,
87,
5349,
2520,
3896,
16,
315,
30746,
1297,
506,
2695,
358,
312,
474,
8863,
203,
1377,
2254,
5034,
14467,
273,
2078,
3088,
1283,
5621,
203,
1377,
2583,
12443,
2859,
1283,
397,
1147,
1380,
13,
1648,
399,
19851,
67,
13272,
23893,
16,
315,
424,
5288,
87,
943,
14467,
8863,
203,
1377,
2583,
12443,
8694,
380,
1147,
1380,
13,
1648,
1234,
18,
1132,
16,
315,
1584,
44,
460,
5177,
1404,
3434,
8863,
203,
1377,
309,
12,
12202,
5349,
2520,
3896,
13,
288,
203,
3639,
2254,
389,
17956,
58,
77,
17842,
329,
1380,
273,
4463,
58,
77,
17842,
329,
1380,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
24899,
17956,
58,
77,
17842,
329,
1380,
405,
374,
16,
315,
1248,
603,
776,
2579,
666,
4869,
1846,
1240,
1818,
312,
474,
329,
8863,
203,
3639,
2583,
12,
2316,
1380,
1648,
389,
17956,
58,
77,
17842,
329,
1380,
16,
315,
424,
5288,
87,
943,
777,
352,
2344,
1056,
316,
776,
2579,
666,
8863,
203,
3639,
13206,
17842,
63,
3576,
18,
15330,
8009,
5332,
49,
474,
329,
273,
13206,
17842,
63,
3576,
18,
15330,
8009,
5332,
49,
474,
329,
397,
1147,
1380,
31,
203,
3639,
2583,
12,
2316,
1380,
1648,
943,
4782,
49,
474,
2173,
4188,
16,
315,
424,
5288,
87,
943,
1056,
1534,
2492,
8863,
203,
1377,
289,
203,
203,
1377,
2254,
277,
31,
203,
1377,
364,
261,
77,
273,
404,
31,
277,
1648,
1147,
1380,
31,
277,
27245,
2
] |
./full_match/4/0x208426c2B281aC34f7005A03f638F43C6489505e/sources/contracts/lib/balancer/configurable-rights-pool/libraries/RightsManager.sol | * @author Balancer Labs @title Manage Configurable Rights for the smart pool canPauseSwapping - can setPublicSwap back to false after turning it on by default, it is off on initialization and can only be turned on canChangeSwapFee - can setSwapFee after initialization (by default, it is fixed at create time) canChangeWeights - can bind new token weights (allowed by default in base pool) canAddRemoveTokens - can bind/unbind tokens (allowed by default in base pool) canWhitelistLPs - can limit liquidity providers to a given set of addresses canChangeCap - can change the BSP cap (max # of pool tokens)/ Type declarations | library RightsManager {
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
enum Permissions { PAUSE_SWAPPING, CHANGE_SWAP_FEE, CHANGE_WEIGHTS, ADD_REMOVE_TOKENS, WHITELIST_LPS, CHANGE_CAP }
struct Rights {
bool canPauseSwapping;
bool canChangeSwapFee;
bool canChangeWeights;
bool canAddRemoveTokens;
bool canWhitelistLPs;
bool canChangeCap;
}
bool public constant DEFAULT_CAN_CHANGE_SWAP_FEE = true;
bool public constant DEFAULT_CAN_CHANGE_WEIGHTS = true;
bool public constant DEFAULT_CAN_ADD_REMOVE_TOKENS = false;
bool public constant DEFAULT_CAN_WHITELIST_LPS = false;
bool public constant DEFAULT_CAN_CHANGE_CAP = false;
bool public constant DEFAULT_CAN_PAUSE_SWAPPING = false;
function constructRights(bool[] calldata a) external pure returns (Rights memory) {
if (a.length == 0) {
return
Rights(
DEFAULT_CAN_PAUSE_SWAPPING,
DEFAULT_CAN_CHANGE_SWAP_FEE,
DEFAULT_CAN_CHANGE_WEIGHTS,
DEFAULT_CAN_ADD_REMOVE_TOKENS,
DEFAULT_CAN_WHITELIST_LPS,
DEFAULT_CAN_CHANGE_CAP
);
return Rights(a[0], a[1], a[2], a[3], a[4], a[5]);
}
}
function constructRights(bool[] calldata a) external pure returns (Rights memory) {
if (a.length == 0) {
return
Rights(
DEFAULT_CAN_PAUSE_SWAPPING,
DEFAULT_CAN_CHANGE_SWAP_FEE,
DEFAULT_CAN_CHANGE_WEIGHTS,
DEFAULT_CAN_ADD_REMOVE_TOKENS,
DEFAULT_CAN_WHITELIST_LPS,
DEFAULT_CAN_CHANGE_CAP
);
return Rights(a[0], a[1], a[2], a[3], a[4], a[5]);
}
}
} else {
function convertRights(Rights calldata rights) external pure returns (bool[] memory) {
bool[] memory result = new bool[](6);
result[0] = rights.canPauseSwapping;
result[1] = rights.canChangeSwapFee;
result[2] = rights.canChangeWeights;
result[3] = rights.canAddRemoveTokens;
result[4] = rights.canWhitelistLPs;
result[5] = rights.canChangeCap;
return result;
}
function hasPermission(Rights calldata self, Permissions permission) external pure returns (bool) {
if (Permissions.PAUSE_SWAPPING == permission) {
return self.canPauseSwapping;
return self.canChangeSwapFee;
return self.canChangeWeights;
return self.canAddRemoveTokens;
return self.canWhitelistLPs;
return self.canChangeCap;
}
}
function hasPermission(Rights calldata self, Permissions permission) external pure returns (bool) {
if (Permissions.PAUSE_SWAPPING == permission) {
return self.canPauseSwapping;
return self.canChangeSwapFee;
return self.canChangeWeights;
return self.canAddRemoveTokens;
return self.canWhitelistLPs;
return self.canChangeCap;
}
}
} else if (Permissions.CHANGE_SWAP_FEE == permission) {
} else if (Permissions.CHANGE_WEIGHTS == permission) {
} else if (Permissions.ADD_REMOVE_TOKENS == permission) {
} else if (Permissions.WHITELIST_LPS == permission) {
} else if (Permissions.CHANGE_CAP == permission) {
}
| 12,288,092 | [
1,
6444,
511,
5113,
225,
24247,
29312,
534,
10730,
364,
326,
13706,
2845,
1377,
848,
19205,
12521,
1382,
300,
848,
27467,
12521,
1473,
358,
629,
1839,
7005,
310,
518,
603,
7682,
635,
805,
16,
518,
353,
3397,
603,
10313,
471,
848,
1338,
506,
21826,
603,
1377,
848,
3043,
12521,
14667,
300,
848,
444,
12521,
14667,
1839,
10313,
261,
1637,
805,
16,
518,
353,
5499,
622,
752,
813,
13,
1377,
848,
3043,
16595,
300,
848,
1993,
394,
1147,
5376,
261,
8151,
635,
805,
316,
1026,
2845,
13,
1377,
848,
986,
3288,
5157,
300,
848,
1993,
19,
318,
4376,
2430,
261,
8151,
635,
805,
316,
1026,
2845,
13,
1377,
848,
18927,
14461,
87,
300,
848,
1800,
4501,
372,
24237,
9165,
358,
279,
864,
444,
434,
6138,
1377,
848,
3043,
4664,
300,
848,
2549,
326,
605,
3118,
3523,
261,
1896,
225,
434,
2845,
2430,
13176,
1412,
12312,
2,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0
] | [
1,
12083,
534,
10730,
1318,
288,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
2138,
31,
203,
683,
9454,
23070,
10336,
45,
7204,
58,
22,
31,
203,
225,
2792,
15684,
288,
15662,
8001,
67,
18746,
15263,
16,
26267,
67,
18746,
2203,
67,
8090,
41,
16,
26267,
67,
29988,
55,
16,
11689,
67,
22122,
67,
8412,
55,
16,
24353,
7085,
67,
48,
5857,
16,
26267,
67,
17296,
289,
203,
225,
1958,
534,
10730,
288,
203,
565,
1426,
848,
19205,
12521,
1382,
31,
203,
565,
1426,
848,
3043,
12521,
14667,
31,
203,
565,
1426,
848,
3043,
16595,
31,
203,
565,
1426,
848,
986,
3288,
5157,
31,
203,
565,
1426,
848,
18927,
14461,
87,
31,
203,
565,
1426,
848,
3043,
4664,
31,
203,
225,
289,
203,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
14473,
67,
18746,
2203,
67,
8090,
41,
273,
638,
31,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
14473,
67,
29988,
55,
273,
638,
31,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
8355,
67,
22122,
67,
8412,
55,
273,
629,
31,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
16861,
7085,
67,
48,
5857,
273,
629,
31,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
14473,
67,
17296,
273,
629,
31,
203,
203,
225,
1426,
1071,
5381,
3331,
67,
39,
1258,
67,
4066,
8001,
67,
18746,
15263,
273,
629,
31,
203,
203,
225,
445,
4872,
18464,
12,
6430,
8526,
745,
892,
279,
13,
3903,
16618,
1135,
261,
18464,
3778,
13,
2
] |
./partial_match/1/0x1E6EB746EC5dbDe097223dD1bb3031310321e33B/sources/UreeqaCollectibleNFTv2.sol | @dev Create a resolution to add an owner. Performs addition if threshold is 1 or zero. | function createResolutionAddOwner(address newOwner) public onlyOwners() {
isValidAddress(newOwner);
require(
!EnumerableSet.contains(_owners, newOwner),
"newOwner already exists."
);
createResolution(resTypeAddOwner, address(0), newOwner, new bytes32[](0));
}
| 2,597,298 | [
1,
1684,
279,
7861,
358,
527,
392,
3410,
18,
27391,
2719,
309,
5573,
353,
404,
578,
3634,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
752,
11098,
986,
5541,
12,
2867,
394,
5541,
13,
1071,
1338,
5460,
414,
1435,
288,
203,
3639,
4908,
1887,
12,
2704,
5541,
1769,
203,
3639,
2583,
12,
203,
5411,
401,
3572,
25121,
694,
18,
12298,
24899,
995,
414,
16,
394,
5541,
3631,
203,
5411,
315,
2704,
5541,
1818,
1704,
1199,
203,
3639,
11272,
203,
203,
3639,
752,
11098,
12,
455,
559,
986,
5541,
16,
1758,
12,
20,
3631,
394,
5541,
16,
394,
1731,
1578,
8526,
12,
20,
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
] |
pragma solidity ^0.4.19;
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() {
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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @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);
}
library KeysUtils {
// Such order is important to load from state
struct Object {
uint32 gasPriceGwei;
uint32 gasLimit;
uint32 timestamp;
address contractAddress;
}
function toKey(Object _obj) internal pure returns (bytes32) {
return toKey(_obj.contractAddress, _obj.timestamp, _obj.gasLimit, _obj.gasPriceGwei);
}
function toKeyFromStorage(Object storage _obj) internal view returns (bytes32 _key) {
assembly {
_key := sload(_obj_slot)
}
}
function toKey(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal pure returns (bytes32 result) {
result = 0x0000000000000000000000000000000000000000000000000000000000000000;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - address (20 bytes)
// ^^^^^^^^ - timestamp (4 bytes)
// ^^^^^^^^ - gas limit (4 bytes)
// ^^^^^^^^ - gas price (4 bytes)
assembly {
result := or(result, mul(_address, 0x1000000000000000000000000))
result := or(result, mul(and(_timestamp, 0xffffffff), 0x10000000000000000))
result := or(result, mul(and(_gasLimit, 0xffffffff), 0x100000000))
result := or(result, and(_gasPrice, 0xffffffff))
}
}
function toMemoryObject(bytes32 _key, Object memory _dest) internal pure {
assembly {
mstore(_dest, and(_key, 0xffffffff))
mstore(add(_dest, 0x20), and(div(_key, 0x100000000), 0xffffffff))
mstore(add(_dest, 0x40), and(div(_key, 0x10000000000000000), 0xffffffff))
mstore(add(_dest, 0x60), div(_key, 0x1000000000000000000000000))
}
}
function toObject(bytes32 _key) internal pure returns (Object memory _dest) {
toMemoryObject(_key, _dest);
}
function toStateObject(bytes32 _key, Object storage _dest) internal {
assembly {
sstore(_dest_slot, _key)
}
}
function getTimestamp(bytes32 _key) internal pure returns (uint result) {
assembly {
result := and(div(_key, 0x10000000000000000), 0xffffffff)
}
}
}
contract TransferToken is Ownable {
function transferToken(ERC20Basic _token, address _to, uint _value) public onlyOwner {
_token.transfer(_to, _value);
}
}
contract JouleProxyAPI {
/**
* Function hash is: 0x73027f6d
*/
function callback(address _contract) public;
}
contract CheckableContract {
event Checked();
/*
* Function hash is 0x919840ad.
*/
function check() public;
}
contract JouleAPI {
event Invoked(address indexed _address, bool _status, uint _usedGas);
event Registered(address indexed _address, uint _timestamp, uint _gasLimit, uint _gasPrice);
/**
* @dev Registers the specified contract to invoke at the specified time with the specified gas and price.
* @notice It required amount of ETH as value, to cover gas usage. See getPrice method.
*
* @param _address Contract's address. Contract MUST implements Checkable interface.
* @param _timestamp Timestamp at what moment contract should be called. It MUST be in future.
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
*/
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint);
/**
* @dev Invokes next contracts in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invoke() public returns (uint);
/**
* @dev Invokes the top contract in the queue.
* @notice Eth amount to cover gas will be returned if gas price is equal or less then specified for contract. Check getTop for right gas price.
* @return Reward amount.
*/
function invokeTop() public returns (uint);
/**
* @dev Calculates required to register amount of WEI.
*
* @param _gasLimit Gas which will be posted to call.
* @param _gasPrice Gas price which is recommended to use for this invocation.
* @return Amount in wei.
*/
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint);
/**
* @dev Gets how many contracts are registered (and not invoked).
*/
function getCount() public view returns (uint);
/**
* @dev Gets top contract (the next to invoke).
*
* @return contractAddress The contract address.
* @return timestamp The invocation timestamp.
* @return gasLimit The invocation maximum gas.
* @return gasPrice The invocation expected price.
*/
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
);
/**
* @dev Gets top _count contracts (in order to invoke).
*
* @param _count How many records will be returned.
* @return addresses The contracts addresses.
* @return timestamps The invocation timestamps.
* @return gasLimits The invocation gas limits.
* @return gasPrices The invocation expected prices.
*/
function getTop(uint _count) external view returns (
address[] addresses,
uint[] timestamps,
uint[] gasLimits,
uint[] gasPrices
);
/**
* @dev Gets actual code version.
* @return Code version. Mask: 0xff.0xff.0xffff-0xffffffff (major.minor.build-hash)
*/
function getVersion() external view returns (bytes8);
}
contract usingConsts {
uint constant GWEI = 0.001 szabo;
// this value influence to the reward price! do not change for already registered contracts!
uint constant IDLE_GAS = 22273;
uint constant MAX_GAS = 4000000;
// Code version
bytes8 constant VERSION = 0x0100001300000000;
// ^^ - major
// ^^ - minor
// ^^^^ - build
// ^^^^^^^^ - git hash
}
contract JouleIndex {
using KeysUtils for bytes32;
uint constant YEAR = 0x1DFE200;
// year -> month -> day -> hour
mapping (bytes32 => bytes32) index;
bytes32 head;
function insert(bytes32 _key) public {
uint timestamp = _key.getTimestamp();
bytes32 year = toKey(timestamp, YEAR);
bytes32 headLow;
bytes32 headHigh;
(headLow, headHigh) = fromValue(head);
if (year < headLow || headLow == 0 || year > headHigh) {
if (year < headLow || headLow == 0) {
headLow = year;
}
if (year > headHigh) {
headHigh = year;
}
head = toValue(headLow, headHigh);
}
bytes32 week = toKey(timestamp, 1 weeks);
bytes32 low;
bytes32 high;
(low, high) = fromValue(index[year]);
if (week < low || week > high) {
if (week < low || low == 0) {
low = week;
}
if (week > high) {
high = week;
}
index[year] = toValue(low, high);
}
(low, high) = fromValue(index[week]);
bytes32 hour = toKey(timestamp, 1 hours);
if (hour < low || hour > high) {
if (hour < low || low == 0) {
low = hour;
}
if (hour > high) {
high = hour;
}
index[week] = toValue(low, high);
}
(low, high) = fromValue(index[hour]);
bytes32 minute = toKey(timestamp, 1 minutes);
if (minute < low || minute > high) {
if (minute < low || low == 0) {
low = minute;
}
if (minute > high) {
high = minute;
}
index[hour] = toValue(low, high);
}
(low, high) = fromValue(index[minute]);
bytes32 tsKey = toKey(timestamp);
if (tsKey < low || tsKey > high) {
if (tsKey < low || low == 0) {
low = tsKey;
}
if (tsKey > high) {
high = tsKey;
}
index[minute] = toValue(low, high);
}
index[tsKey] = _key;
}
function findFloorKeyYear(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 year = toKey(_timestamp, YEAR);
if (year < _low) {
return 0;
}
if (year > _high) {
// week
(low, high) = fromValue(index[_high]);
// hour
(low, high) = fromValue(index[high]);
// minute
(low, high) = fromValue(index[high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
bytes32 low;
bytes32 high;
while (year >= _low) {
(low, high) = fromValue(index[year]);
if (low != 0) {
bytes32 key = findFloorKeyWeek(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 0x1DFE200 = 52 weeks = 31449600
assembly {
year := sub(year, 0x1DFE200)
}
}
return 0;
}
function findFloorKeyWeek(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 week = toKey(_timestamp, 1 weeks);
if (week < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (week > _high) {
// hour
(low, high) = fromValue(index[_high]);
// minute
(low, high) = fromValue(index[high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
while (week >= _low) {
(low, high) = fromValue(index[week]);
if (low != 0) {
bytes32 key = findFloorKeyHour(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 weeks = 604800
assembly {
week := sub(week, 604800)
}
}
return 0;
}
function findFloorKeyHour(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 hour = toKey(_timestamp, 1 hours);
if (hour < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (hour > _high) {
// minute
(low, high) = fromValue(index[_high]);
// ts
(low, high) = fromValue(index[high]);
return index[high];
}
while (hour >= _low) {
(low, high) = fromValue(index[hour]);
if (low != 0) {
bytes32 key = findFloorKeyMinute(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 hours = 3600
assembly {
hour := sub(hour, 3600)
}
}
return 0;
}
function findFloorKeyMinute(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 minute = toKey(_timestamp, 1 minutes);
if (minute < _low) {
return 0;
}
bytes32 low;
bytes32 high;
if (minute > _high) {
// ts
(low, high) = fromValue(index[_high]);
return index[high];
}
while (minute >= _low) {
(low, high) = fromValue(index[minute]);
if (low != 0) {
bytes32 key = findFloorKeyTimestamp(_timestamp, low, high);
if (key != 0) {
return key;
}
}
// 1 minutes = 60
assembly {
minute := sub(minute, 60)
}
}
return 0;
}
function findFloorKeyTimestamp(uint _timestamp, bytes32 _low, bytes32 _high) view internal returns (bytes32) {
bytes32 tsKey = toKey(_timestamp);
if (tsKey < _low) {
return 0;
}
if (tsKey > _high) {
return index[_high];
}
while (tsKey >= _low) {
bytes32 key = index[tsKey];
if (key != 0) {
return key;
}
assembly {
tsKey := sub(tsKey, 1)
}
}
return 0;
}
function findFloorKey(uint _timestamp) view public returns (bytes32) {
// require(_timestamp > 0xffffffff);
// if (_timestamp < 1515612415) {
// return 0;
// }
bytes32 yearLow;
bytes32 yearHigh;
(yearLow, yearHigh) = fromValue(head);
return findFloorKeyYear(_timestamp, yearLow, yearHigh);
}
function toKey(uint _timestamp, uint rounder) pure internal returns (bytes32 result) {
// 0x0...00000000000000000
// ^^^^^^^^ - rounder marker (eg, to avoid crossing first day of year with year)
// ^^^^^^^^ - rounded moment (year, week, etc)
assembly {
result := or(mul(rounder, 0x100000000), mul(div(_timestamp, rounder), rounder))
}
}
function toValue(bytes32 _lowKey, bytes32 _highKey) pure internal returns (bytes32 result) {
assembly {
result := or(mul(_lowKey, 0x10000000000000000), _highKey)
}
}
function fromValue(bytes32 _value) pure internal returns (bytes32 _lowKey, bytes32 _highKey) {
assembly {
_lowKey := and(div(_value, 0x10000000000000000), 0xffffffffffffffff)
_highKey := and(_value, 0xffffffffffffffff)
}
}
function toKey(uint timestamp) pure internal returns (bytes32) {
return bytes32(timestamp);
}
}
contract JouleContractHolder is usingConsts {
using KeysUtils for bytes32;
// event Found(uint timestamp);
uint internal length;
bytes32 head;
mapping (bytes32 => bytes32) objects;
JouleIndex index;
function JouleContractHolder() public {
index = new JouleIndex();
}
function insert(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) internal {
length ++;
bytes32 id = KeysUtils.toKey(_address, _timestamp, _gasLimit, _gasPrice);
if (head == 0) {
head = id;
index.insert(id);
// Found(0xffffffff);
return;
}
bytes32 previous = index.findFloorKey(_timestamp);
// reject duplicate key on the end
require(previous != id);
// reject duplicate in the middle
require(objects[id] == 0);
uint prevTimestamp = previous.getTimestamp();
// Found(prevTimestamp);
uint headTimestamp = head.getTimestamp();
// add as head, prevTimestamp == 0 or in the past
if (prevTimestamp < headTimestamp) {
objects[id] = head;
head = id;
}
// add after the previous
else {
objects[id] = objects[previous];
objects[previous] = id;
}
index.insert(id);
}
function next() internal returns (KeysUtils.Object memory _next) {
head = objects[head];
length--;
_next = head.toObject();
}
function getCount() public view returns (uint) {
return length;
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices
) {
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
bytes32 current = head;
for (uint i = 0; i < amount; i ++) {
KeysUtils.Object memory obj = current.toObject();
_addresses[i] = obj.contractAddress;
_timestamps[i] = obj.timestamp;
_gasLimits[i] = obj.gasLimit;
_gasPrices[i] = obj.gasPriceGwei * GWEI;
current = objects[current];
}
}
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
KeysUtils.Object memory obj = head.toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
}
function getNext(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
if (_timestamp == 0) {
return this.getTop();
}
bytes32 prev = KeysUtils.toKey(_contractAddress, _timestamp, _gasLimit, _gasPrice / GWEI);
bytes32 current = objects[prev];
KeysUtils.Object memory obj = current.toObject();
contractAddress = obj.contractAddress;
timestamp = obj.timestamp;
gasLimit = obj.gasLimit;
gasPrice = obj.gasPriceGwei * GWEI;
}
}
contract Joule is JouleAPI, JouleContractHolder {
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
uint price = this.getPrice(_gasLimit, _gasPrice);
require(msg.value >= price);
require(_timestamp > now);
require(_timestamp < 0x100000000);
require(_gasLimit < MAX_GAS);
// from 1 gwei to 0x100000000 gwei
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
insert(_address, _timestamp, _gasLimit, _gasPrice / GWEI);
Registered(_address, _timestamp, _gasLimit, _gasPrice);
if (msg.value > price) {
msg.sender.transfer(msg.value - price);
return msg.value - price;
}
return 0;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
require(_gasLimit < 4300000);
require(_gasPrice > GWEI);
require(_gasPrice < 0x100000000 * GWEI);
return getPriceInner(_gasLimit, _gasPrice);
}
function getPriceInner(uint _gasLimit, uint _gasPrice) internal pure returns (uint) {
return (_gasLimit + IDLE_GAS) * _gasPrice;
}
function invoke() public returns (uint) {
return innerInvoke(invokeCallback);
}
function invokeTop() public returns (uint) {
return innerInvokeTop(invokeCallback);
}
function getVersion() external view returns (bytes8) {
return VERSION;
}
function innerInvoke(function (address, uint) internal returns (bool) _callback) internal returns (uint _amount) {
KeysUtils.Object memory current = KeysUtils.toObject(head);
uint amount;
while (current.timestamp != 0 && current.timestamp < now && msg.gas >= current.gasLimit) {
uint gas = msg.gas;
bool status = _callback(current.contractAddress, current.gasLimit);
// current.contractAddress.call.gas(current.gasLimit)(0x919840ad);
gas -= msg.gas;
Invoked(current.contractAddress, status, gas);
amount += getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
current = next();
}
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function innerInvokeTop(function (address, uint) internal returns (bool) _callback) internal returns (uint _amount) {
KeysUtils.Object memory current = KeysUtils.toObject(head);
uint gas = msg.gas;
bool status = _callback(current.contractAddress, current.gasLimit);
gas -= msg.gas;
Invoked(current.contractAddress, status, gas);
uint amount = getPriceInner(current.gasLimit, current.gasPriceGwei * GWEI);
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function invokeCallback(address _contract, uint _gas) internal returns (bool) {
return _contract.call.gas(_gas)(0x919840ad);
}
}
contract JouleBehindProxy is Joule, Ownable, TransferToken {
address public proxy;
function setProxy(address _proxy) public onlyOwner {
proxy = _proxy;
}
modifier onlyProxy() {
require(msg.sender == proxy);
_;
}
function invoke() public onlyProxy returns (uint) {
return super.invoke();
}
function invokeTop() public onlyProxy returns (uint) {
return super.invokeTop();
}
function invokeCallback(address _contract, uint _gas) internal returns (bool) {
return proxy.call.gas(_gas)(0x73027f6d, _contract);
}
}
contract JouleProxy is JouleProxyAPI, JouleAPI, Ownable, TransferToken {
JouleBehindProxy public joule;
function setJoule(JouleBehindProxy _joule) public onlyOwner {
joule = _joule;
}
modifier onlyJoule() {
require(msg.sender == address(joule));
_;
}
function () public payable onlyJoule {
}
function getCount() public view returns (uint) {
return joule.getCount();
}
function register(address _address, uint _timestamp, uint _gasLimit, uint _gasPrice) external payable returns (uint) {
uint change = joule.register.value(msg.value)(_address, _timestamp, _gasLimit, _gasPrice);
if (change > 0) {
msg.sender.transfer(change);
}
return change;
}
function invoke() public returns (uint) {
uint amount = joule.invoke();
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function invokeTop() public returns (uint) {
uint amount = joule.invokeTop();
if (amount > 0) {
msg.sender.transfer(amount);
}
return amount;
}
function getPrice(uint _gasLimit, uint _gasPrice) external view returns (uint) {
return joule.getPrice(_gasLimit, _gasPrice);
}
function getTop() external view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getTop();
}
function getNext(address _contractAddress,
uint _timestamp,
uint _gasLimit,
uint _gasPrice) public view returns (
address contractAddress,
uint timestamp,
uint gasLimit,
uint gasPrice
) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getNext(_contractAddress, _timestamp, _gasLimit, _gasPrice);
}
function getTop(uint _count) external view returns (
address[] _addresses,
uint[] _timestamps,
uint[] _gasLimits,
uint[] _gasPrices
) {
uint length = joule.getCount();
uint amount = _count <= length ? _count : length;
_addresses = new address[](amount);
_timestamps = new uint[](amount);
_gasLimits = new uint[](amount);
_gasPrices = new uint[](amount);
address contractAddress;
uint timestamp;
uint gasLimit;
uint gasPrice;
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getTop();
_addresses[0] = contractAddress;
_timestamps[0] = timestamp;
_gasLimits[0] = gasLimit;
_gasPrices[0] = gasPrice;
for (uint i = 1; i < amount; i ++) {
(contractAddress, timestamp, gasLimit, gasPrice) = joule.getNext(contractAddress, timestamp, gasLimit, gasPrice);
_addresses[i] = contractAddress;
_timestamps[i] = timestamp;
_gasLimits[i] = gasLimit;
_gasPrices[i] = gasPrice;
}
}
function getVersion() external view returns (bytes8) {
return joule.getVersion();
}
function callback(address _contract) public onlyJoule {
CheckableContract(_contract).check();
}
} | require(_timestamp > 0xffffffff); if (_timestamp < 1515612415) { return 0; } | function findFloorKey(uint _timestamp) view public returns (bytes32) {
bytes32 yearLow;
bytes32 yearHigh;
(yearLow, yearHigh) = fromValue(head);
return findFloorKeyYear(_timestamp, yearLow, yearHigh);
}
| 13,003,634 | [
1,
6528,
24899,
5508,
405,
374,
28857,
1769,
3639,
309,
261,
67,
5508,
411,
4711,
28946,
24734,
3600,
13,
288,
5411,
327,
374,
31,
3639,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1104,
42,
5807,
653,
12,
11890,
389,
5508,
13,
1476,
1071,
1135,
261,
3890,
1578,
13,
288,
203,
203,
3639,
1731,
1578,
3286,
10520,
31,
203,
3639,
1731,
1578,
3286,
8573,
31,
203,
3639,
261,
6874,
10520,
16,
3286,
8573,
13,
273,
628,
620,
12,
1978,
1769,
203,
203,
3639,
327,
1104,
42,
5807,
653,
5593,
24899,
5508,
16,
3286,
10520,
16,
3286,
8573,
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
] |
./full_match/42/0xE5EC053962E4A3b31F5b69B766c1e23166F2388D/sources/Users/225153/Projects/ram/contracts/RamVault.sol | uint256 newRewards = ram.balanceOf(_amount).sub(ramBalance); ramBalance = ram.balanceOf(address(this)); If there is no change the balance didn't change | function addPendingRewards(uint256 _amount) public {
uint256 newRewards = _amount;
if(newRewards > 0) {
pendingRewards = pendingRewards.add(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards);
}
}
| 16,262,059 | [
1,
11890,
5034,
394,
17631,
14727,
273,
24975,
18,
12296,
951,
24899,
8949,
2934,
1717,
12,
1940,
13937,
1769,
24975,
13937,
273,
24975,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
225,
971,
1915,
353,
1158,
2549,
326,
11013,
10242,
1404,
2549,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
8579,
17631,
14727,
12,
11890,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
2254,
5034,
394,
17631,
14727,
273,
389,
8949,
31,
203,
203,
3639,
309,
12,
2704,
17631,
14727,
405,
374,
13,
288,
203,
5411,
4634,
17631,
14727,
273,
4634,
17631,
14727,
18,
1289,
12,
2704,
17631,
14727,
1769,
203,
5411,
283,
6397,
382,
2503,
14638,
273,
283,
6397,
382,
2503,
14638,
18,
1289,
12,
2704,
17631,
14727,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x582e3d8dcd41f586fbcc6559f16476d20b2a3b95
//Contract name: SCLCrowdsale
//Balance: 0 Ether
//Verification Date: 7/26/2017
//Transacion Count: 5251
// CODE STARTS HERE
contract Token {
function issue(address _recipient, uint256 _value) returns (bool success) {}
function totalSupply() constant returns (uint256 supply) {}
function unlock() returns (bool success) {}
}
contract SCLCrowdsale {
// Crowdsale details
address public beneficiary; // Company address multisig (95% funding)
address public creator; // Creator (5% funding)
address public confirmedBy; // Address that confirmed beneficiary
uint256 public minAmount = 294 ether; // ≈ 250k SCL
uint256 public maxAmount = 100000 ether; // ≈ 50 mln SCL
uint256 public maxSupply = 50000000 * 10**8; // 50 mln SCL
uint256 public minAcceptedAmount = 40 finney; // 1/25 ether
// Eth to SCL rate
uint256 public ratePreICO = 850;
uint256 public rateWaiting = 0;
uint256 public rateAngelDay = 750;
uint256 public rateFirstWeek = 700;
uint256 public rateSecondWeek = 650;
uint256 public rateThirdWeek = 600;
uint256 public rateLastWeek = 550;
uint256 public ratePreICOEnd = 10 days;
uint256 public rateWaitingEnd = 20 days;
uint256 public rateAngelDayEnd = 21 days;
uint256 public rateFirstWeekEnd = 28 days;
uint256 public rateSecondWeekEnd = 35 days;
uint256 public rateThirdWeekEnd = 42 days;
uint256 public rateLastWeekEnd = 49 days;
enum Stages {
InProgress,
Ended,
Withdrawn
}
Stages public stage = Stages.InProgress;
// Crowdsale state
uint256 public start;
uint256 public end;
uint256 public raised;
// SCL token
Token public sclToken;
// Invested balances
mapping (address => uint256) balances;
/**
* Throw if at stage other than current stage
*
* @param _stage expected stage to test for
*/
modifier atStage(Stages _stage) {
if (stage != _stage) {
throw;
}
_;
}
/**
* Throw if sender is not beneficiary
*/
modifier onlyBeneficiary() {
if (beneficiary != msg.sender) {
throw;
}
_;
}
/**
* Get balance of `_investor`
*
* @param _investor The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address _investor) constant returns (uint256 balance) {
return balances[_investor];
}
/**
* Construct
*
* @param _tokenAddress The address of the SCL token contact
*/
function SCLCrowdsale(address _tokenAddress, address _beneficiary, address _creator, uint256 _start) {
sclToken = Token(_tokenAddress);
beneficiary = _beneficiary;
creator = _creator;
start = _start;
end = start + rateLastWeekEnd;
}
/**
* For testing purposes
*
* @return The beneficiary address
*/
function confirmBeneficiary() onlyBeneficiary {
confirmedBy = msg.sender;
}
/**
* Convert `_wei` to an amount in SCL using
* the current rate
*
* @param _wei amount of wei to convert
* @return The amount in SCL
*/
function toSCL(uint256 _wei) returns (uint256 amount) {
uint256 rate = 0;
if (stage != Stages.Ended && now >= start && now <= end) {
// Check for preico
if (now <= start + ratePreICOEnd) {
rate = ratePreICO;
}
// Check for waiting period
else if (now <= start + rateWaitingEnd) {
rate = rateWaiting;
}
// Check for angelday
else if (now <= start + rateAngelDayEnd) {
rate = rateAngelDay;
}
// Check first week
else if (now <= start + rateFirstWeekEnd) {
rate = rateFirstWeek;
}
// Check second week
else if (now <= start + rateSecondWeekEnd) {
rate = rateSecondWeek;
}
// Check third week
else if (now <= start + rateThirdWeekEnd) {
rate = rateThirdWeek;
}
// Check last week
else if (now <= start + rateLastWeekEnd) {
rate = rateLastWeek;
}
}
return _wei * rate * 10**8 / 1 ether; // 10**8 for 8 decimals
}
/**
* Function to end the crowdsale by setting
* the stage to Ended
*/
function endCrowdsale() atStage(Stages.InProgress) {
// Crowdsale not ended yet
if (now < end) {
throw;
}
stage = Stages.Ended;
}
/**
* Transfer appropriate percentage of raised amount
* to the company address
*/
function withdraw() onlyBeneficiary atStage(Stages.Ended) {
// Confirm that minAmount is raised
if (raised < minAmount) {
throw;
}
if (!sclToken.unlock()) {
throw;
}
uint256 ethBalance = this.balance;
// 5% eth
uint256 ethFees = ethBalance * 5 / 10**2;
if (!creator.send(ethFees)) {
throw;
}
// 95% eth
if (!beneficiary.send(ethBalance - ethFees)) {
throw;
}
stage = Stages.Withdrawn;
}
/**
* Refund in the case of an unsuccessful crowdsale. The
* crowdsale is considered unsuccessful if minAmount was
* not raised before end
*/
function refund() atStage(Stages.Ended) {
// Only allow refunds if minAmount is not raised
if (raised >= minAmount) {
throw;
}
uint256 receivedAmount = balances[msg.sender];
balances[msg.sender] = 0;
if (receivedAmount > 0 && !msg.sender.send(receivedAmount)) {
balances[msg.sender] = receivedAmount;
}
}
/**
* Receives Eth and issue SCL tokens to the sender
*/
function () payable atStage(Stages.InProgress) {
// Crowdsale not started yet
if (now < start) {
throw;
}
// Crowdsale expired
if (now > end) {
throw;
}
// Enforce min amount
if (msg.value < minAcceptedAmount) {
throw;
}
uint256 received = msg.value;
uint256 valueInSCL = toSCL(msg.value);
// Period between pre-ico and ico
if (valueInSCL == 0) {
throw;
}
if (!sclToken.issue(msg.sender, valueInSCL)) {
throw;
}
// Fees
uint256 sclFees = valueInSCL * 5 / 10**2;
// 5% tokens
if (!sclToken.issue(creator, sclFees)) {
throw;
}
if (now <= start + ratePreICOEnd) {
// Fees
uint256 ethFees = received * 5 / 10**2;
// 5% eth
if (!creator.send(ethFees)) {
throw;
}
// During pre-ico - Non-Refundable
if (!beneficiary.send(received - ethFees)) {
throw;
}
} else {
// During the ICO
balances[msg.sender] += received; // 100% refundable
}
raised += received;
// Check maxAmount raised
if (raised >= maxAmount || sclToken.totalSupply() >= maxSupply) {
stage = Stages.Ended;
}
}
}
| * Receives Eth and issue SCL tokens to the sender/ Crowdsale not started yet Crowdsale expired Enforce min amount Period between pre-ico and ico 5% tokens Fees 5% eth During pre-ico - Non-Refundable Check maxAmount raised | function () payable atStage(Stages.InProgress) {
if (now < start) {
throw;
}
if (now > end) {
throw;
}
if (msg.value < minAcceptedAmount) {
throw;
}
uint256 received = msg.value;
uint256 valueInSCL = toSCL(msg.value);
if (valueInSCL == 0) {
throw;
}
if (!sclToken.issue(msg.sender, valueInSCL)) {
throw;
}
if (!sclToken.issue(creator, sclFees)) {
throw;
}
if (now <= start + ratePreICOEnd) {
uint256 ethFees = received * 5 / 10**2;
if (!creator.send(ethFees)) {
throw;
}
if (!beneficiary.send(received - ethFees)) {
throw;
}
raised += received;
if (raised >= maxAmount || sclToken.totalSupply() >= maxSupply) {
stage = Stages.Ended;
}
}
| 5,507,767 | [
1,
4779,
3606,
512,
451,
471,
5672,
348,
5017,
2430,
358,
326,
5793,
19,
385,
492,
2377,
5349,
486,
5746,
4671,
385,
492,
2377,
5349,
7708,
31716,
1131,
3844,
12698,
3086,
675,
17,
10764,
471,
277,
2894,
1381,
9,
2430,
5782,
281,
1381,
9,
13750,
463,
4017,
675,
17,
10764,
300,
3858,
17,
21537,
429,
2073,
943,
6275,
11531,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1832,
8843,
429,
622,
8755,
12,
31359,
18,
13434,
13,
288,
203,
203,
3639,
309,
261,
3338,
411,
787,
13,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
3338,
405,
679,
13,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
3576,
18,
1132,
411,
1131,
18047,
6275,
13,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
7010,
3639,
2254,
5034,
5079,
273,
1234,
18,
1132,
31,
203,
3639,
2254,
5034,
460,
382,
2312,
48,
273,
358,
2312,
48,
12,
3576,
18,
1132,
1769,
203,
203,
3639,
309,
261,
1132,
382,
2312,
48,
422,
374,
13,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
203,
3639,
309,
16051,
87,
830,
1345,
18,
13882,
12,
3576,
18,
15330,
16,
460,
382,
2312,
48,
3719,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
203,
203,
3639,
309,
16051,
87,
830,
1345,
18,
13882,
12,
20394,
16,
31648,
2954,
281,
3719,
288,
203,
5411,
604,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
3338,
1648,
787,
397,
4993,
1386,
2871,
51,
1638,
13,
288,
203,
203,
5411,
2254,
5034,
13750,
2954,
281,
273,
5079,
380,
1381,
342,
1728,
636,
22,
31,
203,
203,
5411,
309,
16051,
20394,
18,
4661,
12,
546,
2954,
281,
3719,
288,
203,
7734,
604,
31,
203,
5411,
289,
203,
203,
5411,
309,
16051,
70,
4009,
74,
14463,
814,
18,
4661,
12,
15213,
300,
13750,
2954,
281,
3719,
288,
203,
7734,
604,
31,
203,
5411,
289,
203,
203,
203,
2
] |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import { StakingContract } from "./StakingContract.sol";
import { StakingPrecompilesSelectors } from "../lib/StakingPrecompiles.sol";
contract MultipleCallsContract is StakingContract {
struct Delegation {
address validator;
uint256 amount;
}
struct Undelegation {
address validator;
uint256 amount;
}
// given an array of delegations to be made,
// make them
// then collect rewards, if any
function delegateMultipleAndCollectRewards(Delegation[] memory delegations) public returns (bool success) {
success = true;
uint256 length = delegations.length;
Delegation memory delegation;
for(uint256 i = 0; i < length; i ++) {
delegation = delegations[i];
success = _delegate(delegation.validator, delegation.amount) && success;
}
success = _collectRewards() && success;
}
// undelegate from first and delegate to second (amounts may be unequal)
// then collect rewards, if any
function undelegateDelegateAndCollectRewards(Undelegation memory undelegation, Delegation memory delegation) public returns (bool success) {
success = _undelegate(undelegation.validator, undelegation.amount);
success = _delegate(delegation.validator, delegation.amount) && success;
success = _collectRewards() && success;
}
// call multiple times to see the block speed
// assembly is used directly to save gas
// allowing for larger number of calls
function multipleCollectRewards(uint256 howMany) public {
bytes memory encodedInput = abi.encodeWithSelector(StakingPrecompilesSelectors.CollectRewards.selector,
address(this));
bytes32 sizeOfInput;
bytes32 memPtr;
uint256 ignored;
assembly {
sizeOfInput := mload(encodedInput)
memPtr := mload(0x40)
}
for(uint256 i = 0; i < howMany; i ++) {
assembly {
ignored := call(25000,
0xfc,
0x0,
add(encodedInput, 32),
sizeOfInput,
memPtr,
0x20
)
}
}
}
}
| undelegate from first and delegate to second (amounts may be unequal) then collect rewards, if any | function undelegateDelegateAndCollectRewards(Undelegation memory undelegation, Delegation memory delegation) public returns (bool success) {
success = _undelegate(undelegation.validator, undelegation.amount);
success = _delegate(delegation.validator, delegation.amount) && success;
success = _collectRewards() && success;
}
| 14,052,400 | [
1,
1074,
292,
4784,
628,
1122,
471,
7152,
358,
2205,
261,
8949,
87,
2026,
506,
640,
9729,
13,
1508,
3274,
283,
6397,
16,
309,
1281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
225,
445,
640,
22216,
9586,
1876,
10808,
17631,
14727,
12,
984,
3771,
1332,
367,
3778,
640,
3771,
1332,
367,
16,
24117,
367,
3778,
23595,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
565,
2216,
273,
389,
1074,
292,
4784,
12,
1074,
13451,
367,
18,
7357,
16,
640,
3771,
1332,
367,
18,
8949,
1769,
203,
565,
2216,
273,
389,
22216,
12,
3771,
1332,
367,
18,
7357,
16,
23595,
18,
8949,
13,
597,
2216,
31,
203,
565,
2216,
273,
389,
14676,
17631,
14727,
1435,
597,
2216,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x8396aBD91D327F630ccDF3c560aDc0be7dFA8111/sources/contracts/AniGirls.sol | IPFS URL WILL BE ADDED WHEN ANIGIRLS ARE ALL SOLD OUT
| string public ANIGIRLS_PROVENANCE = ""; | 12,284,112 | [
1,
2579,
4931,
1976,
678,
15125,
9722,
11738,
7660,
29707,
8175,
3047,
7937,
3045,
432,
862,
8061,
348,
11846,
8210,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
533,
1071,
8175,
3047,
7937,
3045,
67,
3373,
58,
1157,
4722,
273,
1408,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title A simulator for car sharing
/// @author Elijah T.
/// @notice You can use this contract for only the most basic simulation of car sharing service
/// @dev All function calls are currently implemented without side effects
interface Registerable {
function registerDriver(string memory name, string memory license) external;
}
contract CarSharing is Registerable, Ownable{
/// @notice wallet address mapping to balance of user
mapping ( address => uint ) private balance;
/// @notice wallet address mapping to car rent status of user
mapping ( address => uint ) public rentStatus;
/// @notice wallet address mapping to User struct
mapping ( address => User ) public users;
/// @notice plate No. mapping to Car struct
mapping ( string => Car ) public cars;
/// @notice wallet address mapping to registration status of user
mapping ( address => uint ) public registered;
/// @notice Car struct
struct Car {
bool reserved;
address reservedBy;
}
/// @notice User struct
struct User {
string name;
string license;
bool registered;
bool rented;
bool banned;
}
/// @notice Checks if user is registered
modifier registeredUser() {
require(users[msg.sender].registered, "You have to be registered first");
_;
}
/// @notice Checks if user is unregistered
modifier unregisteredUser() {
require(!users[msg.sender].registered, "You are already registered");
_;
}
/// @notice Checks if driver is currently renting other car
modifier onlyRentOne() {
require(!users[msg.sender].rented, "You can only rent 1 car at a time");
_;
}
/// @notice Checks if user is banned
modifier checkIfBanned() {
require(!users[msg.sender].banned, "You have been banned, please contact support");
_;
}
/// @notice Checks if user has reserved any cars
modifier checkIfRented(string memory plateNo) {
require(cars[plateNo].reserved, "You have not rented any car");
require(cars[plateNo].reservedBy == msg.sender, "You have not rented any car");
_;
}
/// @notice Emitted when a user is registered
/// @param user Account address
/// @param name Name of user
/// @param license Driving license
event UserRegistered(address user, string name, string license);
/// @notice Emitted when a user reserves a car
/// @param user Account address
/// @param plateNo Reserved car plate no.
event CarReserved(address user, string plateNo);
/// @notice Emitted when a user releases a reserved car
/// @param user Account address
/// @param plateNo Reserved car plate no.
event CarReleased(address user, string plateNo);
/// @notice Bans a user with a given wallet address
/// @param _user Wallet address of the user
function banUser(address _user) onlyOwner private
{
users[_user].banned = true;
}
/// @notice Registers a user
/// @param name Name of user
/// @param license Driving license of user
function registerDriver(string memory name, string memory license) public unregisteredUser() {
users[msg.sender] = User({
name: name,
license: license,
registered: true,
rented: false,
banned: false
});
emit UserRegistered(msg.sender, name, license);
}
/// @notice Releases a reserved car
/// @param plateNo Plate No. of reserved car
function unrentCar(string memory plateNo) public payable registeredUser() checkIfRented(plateNo) checkIfBanned(){
uint refundAmount = balance[msg.sender];
balance[msg.sender] = 0;
users[msg.sender].rented = false;
cars[plateNo].reserved = false;
payable(msg.sender).call{ value: refundAmount};
emit CarReleased(msg.sender, plateNo);
}
/// @notice Reserves a car
/// @param fee Reserve fee
/// @param plateNo Plate No. of unreserved car
function rentCar(uint fee, string memory plateNo) public payable registeredUser() onlyRentOne() checkIfBanned(){
balance[msg.sender] += fee;
users[msg.sender].rented = true;
cars[plateNo].reserved = true;
cars[plateNo].reservedBy = msg.sender;
emit CarReserved(msg.sender, plateNo);
}
/// @notice Return balance of user
function getBalance() public view returns (uint) {
return balance[msg.sender];
}
/// @notice Return reserve status of user
/// @param _user Wallet address of user
function getRentStatus(address _user) public view returns (bool) {
return users[_user].rented;
}
/// @notice Return registration status of user
/// @param _user Wallet address of user
function getRegistrationStatus(address _user) public view returns (bool) {
return users[_user].registered;
}
} | @notice Return balance of user | function getBalance() public view returns (uint) {
return balance[msg.sender];
}
| 1,049,326 | [
1,
990,
11013,
434,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
915,
2882,
6112,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
202,
2463,
11013,
63,
3576,
18,
15330,
15533,
203,
97,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x20dA4E7d2A339cec56261fD3152C87C50fABC32B/sources/contracts/HitexStaking.sol | receive amount in $, returns 25% more | function calculateSpHext(uint256 _amount) internal pure returns (uint256) {
return (_amount * 125) / 100;
}
| 11,591,731 | [
1,
18149,
3844,
316,
271,
16,
1135,
6969,
9,
1898,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
4604,
3389,
44,
408,
12,
11890,
5034,
389,
8949,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
261,
67,
8949,
380,
30616,
13,
342,
2130,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { TokenInterface } from "../../common/interfaces.sol";
import { Helpers } from "./helpers.sol";
import { AaveInterface, ATokenInterface, IndexInterface } from "./interfaces.sol";
import { Events } from "./events.sol";
contract LiquidityResolver is Helpers, Events {
using SafeERC20 for IERC20;
function updateVariables(uint _safeRatioGap, uint _fee) public {
require(msg.sender == instaIndex.master(), "not-master");
safeRatioGap = _safeRatioGap;
fee = _fee;
emit LogVariablesUpdate(safeRatioGap, fee);
}
function addTokenSupport(address[] memory _tokens) public {
require(msg.sender == instaIndex.master(), "not-master");
for (uint i = 0; i < supportedTokens.length; i++) {
delete isSupportedToken[supportedTokens[i]];
}
delete supportedTokens;
for (uint i = 0; i < _tokens.length; i++) {
require(!isSupportedToken[_tokens[i]], "already-added");
isSupportedToken[_tokens[i]] = true;
supportedTokens.push(_tokens[i]);
}
emit LogAddSupportedTokens(_tokens);
}
function spell(address _target, bytes memory _data) external {
require(msg.sender == instaIndex.master(), "not-master");
require(_target != address(0), "target-invalid");
assembly {
let succeeded := delegatecall(gas(), _target, add(_data, 0x20), mload(_data), 0, 0)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
let size := returndatasize()
returndatacopy(0x00, 0x00, size)
revert(0x00, size)
}
}
}
/**
* @param _tokens - array of tokens to transfer to L2 receiver's contract
* @param _amts - array of token amounts to transfer to L2 receiver's contract
*/
function settle(address[] calldata _tokens, uint[] calldata _amts) external {
// TODO: Should we use dydx flashloan for easier settlement?
AaveInterface aave = AaveInterface(aaveProvider.getLendingPool());
for (uint i = 0; i < supportedTokens.length; i++) {
address _token = supportedTokens[i];
if (_token == wethAddr) {
if (address(this).balance > 0) {
TokenInterface(wethAddr).deposit{value: address(this).balance}();
}
}
IERC20 _tokenContract = IERC20(_token);
uint _tokenBal = _tokenContract.balanceOf(address(this));
if (_tokenBal > 0) {
_tokenContract.safeApprove(address(aave), _tokenBal);
aave.deposit(_token, _tokenBal, address(this), 3288);
}
(
uint supplyBal,,
uint borrowBal,
,,,,,
) = aaveData.getUserReserveData(_token, address(this));
if (supplyBal != 0 && borrowBal != 0) {
if (supplyBal > borrowBal) {
aave.withdraw(_token, borrowBal, address(this)); // TODO: fail because of not enough withdrawing capacity?
IERC20(_token).safeApprove(address(aave), borrowBal);
aave.repay(_token, borrowBal, 2, address(this));
} else {
aave.withdraw(_token, supplyBal, address(this)); // TODO: fail because of not enough withdrawing capacity?
IERC20(_token).safeApprove(address(aave), supplyBal);
aave.repay(_token, supplyBal, 2, address(this));
}
}
}
for (uint i = 0; i < _tokens.length; i++) {
address _token = _tokens[i] == ethAddr ? wethAddr : _tokens[i];
aave.withdraw(_token, _amts[i], address(this));
if (_token == wethAddr) {
TokenInterface wethContract = TokenInterface(wethAddr);
uint wethBal = wethContract.balanceOf(address(this));
wethContract.approve(wethAddr, wethBal);
wethContract.withdraw(wethBal);
rootChainManager.depositEtherFor{value: _amts[i]}(polygonReceiver);
} else {
IERC20(_token).safeApprove(erc20Predicate, _amts[i]);
rootChainManager.depositFor(polygonReceiver, _tokens[i], abi.encode(_amts[i]));
}
isPositionSafe();
}
emit LogSettle(_tokens, _amts);
}
}
contract MigrateResolver is LiquidityResolver {
using SafeERC20 for IERC20;
function _migrate(
AaveInterface aave,
AaveDataRaw memory _data,
address sourceDsa
) internal {
require(_data.supplyTokens.length > 0, "0-length-not-allowed");
require(_data.targetDsa != address(0), "invalid-address");
require(_data.supplyTokens.length == _data.supplyAmts.length, "invalid-length");
require(
_data.borrowTokens.length == _data.variableBorrowAmts.length &&
_data.borrowTokens.length == _data.stableBorrowAmts.length,
"invalid-length"
);
for (uint i = 0; i < _data.supplyTokens.length; i++) {
address _token = _data.supplyTokens[i];
for (uint j = 0; j < _data.supplyTokens.length; j++) {
if (j != i) {
require(j != i, "token-repeated");
}
}
require(_token != ethAddr, "should-be-eth-address");
}
for (uint i = 0; i < _data.borrowTokens.length; i++) {
address _token = _data.borrowTokens[i];
for (uint j = 0; j < _data.borrowTokens.length; j++) {
if (j != i) {
require(j != i, "token-repeated");
}
}
require(_token != ethAddr, "should-be-eth-address");
}
(uint[] memory stableBorrows, uint[] memory variableBorrows, uint[] memory totalBorrows) = _PaybackCalculate(aave, _data, sourceDsa);
_PaybackStable(_data.borrowTokens.length, aave, _data.borrowTokens, stableBorrows, sourceDsa);
_PaybackVariable(_data.borrowTokens.length, aave, _data.borrowTokens, variableBorrows, sourceDsa);
(uint[] memory totalSupplies) = _getAtokens(sourceDsa, _data.supplyTokens, _data.supplyAmts);
// Aave on Polygon doesn't have stable borrowing so we'll borrow all the debt in variable
AaveData memory data;
data.borrowTokens = _data.borrowTokens;
data.supplyAmts = totalSupplies;
data.supplyTokens = _data.supplyTokens;
data.targetDsa = _data.targetDsa;
data.borrowAmts = totalBorrows;
// Checks the amount that user is trying to migrate is 20% below the Liquidation
_checkRatio(data);
isPositionSafe();
stateSender.syncState(polygonReceiver, abi.encode(data));
emit LogAaveV2Migrate(
sourceDsa,
data.targetDsa,
data.supplyTokens,
data.borrowTokens,
totalSupplies,
variableBorrows,
stableBorrows
);
}
function migrateFlashCallback(AaveDataRaw calldata _data, address dsa, uint ethAmt) external {
require(msg.sender == address(flashloanContract), "not-flashloan-contract");
AaveInterface aave = AaveInterface(aaveProvider.getLendingPool());
TokenInterface wethContract = TokenInterface(wethAddr);
wethContract.approve(address(aave), ethAmt);
aave.deposit(wethAddr, ethAmt, address(this), 3288);
_migrate(aave, _data, dsa);
aave.withdraw(wethAddr, ethAmt, address(this));
require(wethContract.transfer(address(flashloanContract), ethAmt), "migrateFlashCallback: weth transfer failed to Instapool");
}
}
contract InstaAaveV2MigratorSenderImplementation is MigrateResolver {
function migrate(AaveDataRaw calldata _data) external {
AaveInterface aave = AaveInterface(aaveProvider.getLendingPool());
_migrate(aave, _data, msg.sender);
}
function migrateWithFlash(AaveDataRaw calldata _data, uint ethAmt) external {
bytes memory callbackData = abi.encodeWithSelector(bytes4(this.migrateFlashCallback.selector), _data, msg.sender, ethAmt);
bytes memory data = abi.encode(callbackData, ethAmt);
flashloanContract.initiateFlashLoan(data, ethAmt);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint) external returns (bool);
function transferFrom(address, address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
function decimals() external view returns (uint);
}
interface MemoryInterface {
function getUint(uint id) external returns (uint num);
function setUint(uint id, uint val) external;
}
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
import { DSMath } from "../../common/math.sol";
import { Stores } from "../../common/stores-mainnet.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Variables } from "./variables.sol";
import {
AaveLendingPoolProviderInterface,
AaveDataProviderInterface,
AaveInterface,
ATokenInterface,
StateSenderInterface,
AavePriceOracle,
ChainLinkInterface
} from "./interfaces.sol";
abstract contract Helpers is DSMath, Stores, Variables {
using SafeERC20 for IERC20;
function _paybackBehalfOne(AaveInterface aave, address token, uint amt, uint rateMode, address user) private {
address _token = token == ethAddr ? wethAddr : token;
aave.repay(_token, amt, rateMode, user);
}
function _PaybackStable(
uint _length,
AaveInterface aave,
address[] memory tokens,
uint256[] memory amts,
address user
) internal {
for (uint i = 0; i < _length; i++) {
if (amts[i] > 0) {
_paybackBehalfOne(aave, tokens[i], amts[i], 1, user);
}
}
}
function _PaybackVariable(
uint _length,
AaveInterface aave,
address[] memory tokens,
uint256[] memory amts,
address user
) internal {
for (uint i = 0; i < _length; i++) {
if (amts[i] > 0) {
_paybackBehalfOne(aave, tokens[i], amts[i], 2, user);
}
}
}
function _PaybackCalculate(
AaveInterface aave,
AaveDataRaw memory _data,
address sourceDsa
) internal returns (
uint[] memory stableBorrow,
uint[] memory variableBorrow,
uint[] memory totalBorrow
) {
uint _len = _data.borrowTokens.length;
stableBorrow = new uint256[](_len);
variableBorrow = new uint256[](_len);
totalBorrow = new uint256[](_len);
for (uint i = 0; i < _len; i++) {
require(isSupportedToken[_data.borrowTokens[i]], "token-not-enabled");
address _token = _data.borrowTokens[i] == ethAddr ? wethAddr : _data.borrowTokens[i];
_data.borrowTokens[i] = _token;
(
,
uint stableDebt,
uint variableDebt,
,,,,,
) = aaveData.getUserReserveData(_token, sourceDsa);
stableBorrow[i] = _data.stableBorrowAmts[i] == uint(-1) ? stableDebt : _data.stableBorrowAmts[i];
variableBorrow[i] = _data.variableBorrowAmts[i] == uint(-1) ? variableDebt : _data.variableBorrowAmts[i];
totalBorrow[i] = add(stableBorrow[i], variableBorrow[i]);
if (totalBorrow[i] > 0) {
IERC20(_token).safeApprove(address(aave), totalBorrow[i]);
}
aave.borrow(_token, totalBorrow[i], 2, 3288, address(this));
}
}
function _getAtokens(
address dsa,
address[] memory supplyTokens,
uint[] memory supplyAmts
) internal returns (
uint[] memory finalAmts
) {
finalAmts = new uint256[](supplyTokens.length);
for (uint i = 0; i < supplyTokens.length; i++) {
require(isSupportedToken[supplyTokens[i]], "token-not-enabled");
address _token = supplyTokens[i] == ethAddr ? wethAddr : supplyTokens[i];
(address _aToken, ,) = aaveData.getReserveTokensAddresses(_token);
ATokenInterface aTokenContract = ATokenInterface(_aToken);
uint _finalAmt;
if (supplyAmts[i] == uint(-1)) {
_finalAmt = aTokenContract.balanceOf(dsa);
} else {
_finalAmt = supplyAmts[i];
}
require(aTokenContract.transferFrom(dsa, address(this), _finalAmt), "_getAtokens: atokens transfer failed");
_finalAmt = wmul(_finalAmt, fee);
finalAmts[i] = _finalAmt;
}
}
function isPositionSafe() internal view returns (bool isOk) {
AaveInterface aave = AaveInterface(aaveProvider.getLendingPool());
(,,,,,uint healthFactor) = aave.getUserAccountData(address(this));
uint minLimit = wdiv(1e18, safeRatioGap);
isOk = healthFactor > minLimit;
require(isOk, "position-at-risk");
}
function getTokensPrices(address[] memory tokens) internal view returns(uint[] memory tokenPricesInEth) {
tokenPricesInEth = AavePriceOracle(aaveProvider.getPriceOracle()).getAssetsPrices(tokens);
}
// Liquidation threshold
function getTokenLt(address[] memory tokens) internal view returns (uint[] memory decimals, uint[] memory tokenLts) {
uint _len = tokens.length;
decimals = new uint[](_len);
tokenLts = new uint[](_len);
for (uint i = 0; i < _len; i++) {
(decimals[i],,tokenLts[i],,,,,,,) = aaveData.getReserveConfigurationData(tokens[i]);
}
}
function convertTo18(uint amount, uint decimal) internal pure returns (uint) {
return amount * (10 ** (18 - decimal));
}
/*
* Checks the position to migrate should have a safe gap from liquidation
*/
function _checkRatio(AaveData memory data) public view {
uint[] memory supplyTokenPrices = getTokensPrices(data.supplyTokens);
(uint[] memory supplyDecimals, uint[] memory supplyLts) = getTokenLt(data.supplyTokens);
uint[] memory borrowTokenPrices = getTokensPrices(data.borrowTokens);
(uint[] memory borrowDecimals,) = getTokenLt(data.borrowTokens);
uint netSupply;
uint netBorrow;
uint liquidation;
for (uint i = 0; i < data.supplyTokens.length; i++) {
uint _amt = wmul(convertTo18(data.supplyAmts[i], supplyDecimals[i]), supplyTokenPrices[i]);
netSupply += _amt;
liquidation += (_amt * supplyLts[i]) / 10000; // convert the number 8000 to 0.8
}
for (uint i = 0; i < data.borrowTokens.length; i++) {
uint _amt = wmul(convertTo18(data.borrowAmts[i], borrowDecimals[i]), borrowTokenPrices[i]);
netBorrow += _amt;
}
uint _dif = wmul(netSupply, sub(1e18, safeRatioGap));
require(netBorrow < sub(liquidation, _dif), "position-is-risky-to-migrate");
}
}
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;
interface AaveInterface {
function deposit(address _asset, uint256 _amount, address _onBehalfOf, uint16 _referralCode) external;
function withdraw(address _asset, uint256 _amount, address _to) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
function getUserAccountData(address user) external view returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
function getPriceOracle() external view returns (address);
}
// Aave Protocol Data Provider
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset) external view returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user) external view returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveConfigurationData(address asset) external view returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
interface ATokenInterface {
function scaledBalanceOf(address _user) external view returns (uint256);
function isTransferAllowed(address _user, uint256 _amount) external view returns (bool);
function balanceOf(address _user) external view returns(uint256);
function transferFrom(address, address, uint) external returns (bool);
function approve(address, uint256) external;
}
interface AaveOracleInterface {
function getAssetPrice(address _asset) external view returns (uint256);
function getAssetsPrices(address[] calldata _assets) external view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external view returns(address);
function getFallbackOracle() external view returns(address);
}
interface StateSenderInterface {
function syncState(address receiver, bytes calldata data) external;
function register(address sender, address receiver) external;
}
interface IndexInterface {
function master() external view returns (address);
}
interface FlashloanInterface {
function initiateFlashLoan(bytes memory data, uint ethAmt) external;
}
interface AavePriceOracle {
function getAssetPrice(address _asset) external view returns(uint256);
function getAssetsPrices(address[] calldata _assets) external view returns(uint256[] memory);
function getSourceOfAsset(address _asset) external view returns(uint256);
function getFallbackOracle() external view returns(uint256);
}
interface ChainLinkInterface {
function latestAnswer() external view returns (int256);
function decimals() external view returns (uint256);
}
interface RootChainManagerInterface {
function depositFor(address user, address token, bytes calldata depositData) external;
function depositEtherFor(address user) external payable;
}
pragma solidity >=0.7.0;
pragma experimental ABIEncoderV2;
contract Events {
event LogSettle(
address[] tokens,
uint256[] amts
);
event LogAaveV2Migrate(
address indexed user,
address indexed targetDsa,
address[] supplyTokens,
address[] borrowTokens,
uint256[] supplyAmts,
uint256[] variableBorrowAmts,
uint256[] stableBorrowAmts
);
event LogUpdateVariables(
uint256 oldFee,
uint256 newFee,
uint256 oldSafeRatioGap,
uint256 newSafeRatioGap
);
event LogAddSupportedTokens(
address[] tokens
);
event LogVariablesUpdate(uint _safeRatioGap, uint _fee);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity ^0.7.0;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
contract DSMath {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(x, y);
}
function sub(uint x, uint y) internal virtual pure returns (uint z) {
z = SafeMath.sub(x, y);
}
function mul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.mul(x, y);
}
function div(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.div(x, y);
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = SafeMath.add(SafeMath.mul(x, y), RAY / 2) / RAY;
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
}
pragma solidity ^0.7.0;
import { MemoryInterface } from "./interfaces.sol";
abstract contract Stores {
/**
* @dev Return ethereum address
*/
address constant internal ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev Return Wrapped ETH address
*/
address constant internal wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev Return memory variable address
*/
MemoryInterface constant internal instaMemory = MemoryInterface(0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F);
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : instaMemory.getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) virtual internal {
if (setId != 0) instaMemory.setUint(setId, val);
}
}
pragma solidity ^0.7.0;
import {
AaveLendingPoolProviderInterface,
AaveDataProviderInterface,
AaveOracleInterface,
StateSenderInterface,
IndexInterface,
FlashloanInterface,
RootChainManagerInterface
} from "./interfaces.sol";
contract Variables {
// Structs
struct AaveDataRaw {
address targetDsa;
uint[] supplyAmts;
uint[] variableBorrowAmts;
uint[] stableBorrowAmts;
address[] supplyTokens;
address[] borrowTokens;
}
struct AaveData {
address targetDsa;
uint[] supplyAmts;
uint[] borrowAmts;
address[] supplyTokens;
address[] borrowTokens;
}
// Constant Addresses //
/**
* @dev Aave referal code
*/
uint16 constant internal referralCode = 3228;
/**
* @dev Polygon Receiver contract
*/
address constant internal polygonReceiver = 0x4A090897f47993C2504144419751D6A91D79AbF4;
/**
* @dev Flashloan contract
*/
FlashloanInterface constant internal flashloanContract = FlashloanInterface(0xd7e8E6f5deCc5642B77a5dD0e445965B128a585D);
/**
* @dev ERC20 Predicate address
*/
address constant internal erc20Predicate = 0x40ec5B33f54e0E8A33A975908C5BA1c14e5BbbDf;
/**
* @dev Aave Provider
*/
AaveLendingPoolProviderInterface constant internal aaveProvider = AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
/**
* @dev Aave Data Provider
*/
AaveDataProviderInterface constant internal aaveData = AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
/**
* @dev Aave Price Oracle
*/
AaveOracleInterface constant internal aaveOracle = AaveOracleInterface(0xA50ba011c48153De246E5192C8f9258A2ba79Ca9);
/**
* @dev Polygon State Sync Contract
*/
StateSenderInterface constant internal stateSender = StateSenderInterface(0x28e4F3a7f651294B9564800b2D01f35189A5bFbE);
/**
* @dev InstaIndex Address.
*/
IndexInterface public constant instaIndex = IndexInterface(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
/**
* @dev Polygon deposit bridge
*/
RootChainManagerInterface public constant rootChainManager = RootChainManagerInterface(0xA0c68C638235ee32657e8f720a23ceC1bFc77C77);
// Storage variables //
/**
* @dev This will be used to have debt/collateral ratio always 20% less than liquidation
*/
uint public safeRatioGap = 800000000000000000; // 80%
/**
* @dev fee on collateral
*/
uint public fee = 998000000000000000; // 0.2% (99.8%) on collateral
/**
* @dev Mapping of supported token
*/
mapping(address => bool) public isSupportedToken;
/**
* @dev Array of supported token
*/
address[] public supportedTokens; // don't add ethAddr. Only add wethAddr
}
| * @dev Flashloan contract/ | FlashloanInterface constant internal flashloanContract = FlashloanInterface(0xd7e8E6f5deCc5642B77a5dD0e445965B128a585D);
| 5,713,679 | [
1,
11353,
383,
304,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
15014,
383,
304,
1358,
5381,
2713,
9563,
383,
304,
8924,
273,
15014,
383,
304,
1358,
12,
20,
7669,
27,
73,
28,
41,
26,
74,
25,
323,
39,
71,
25,
1105,
22,
38,
4700,
69,
25,
72,
40,
20,
73,
6334,
6162,
9222,
38,
10392,
69,
25,
7140,
40,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/43113/0xcf11cfda20e996b955835B8f0449978a5b546b8e/sources/contracts/CBS.sol | * @dev Same as {get}, with a custom error message when `key` is not in the map. CAUTION: This function is deprecated because it requires allocating memory for the error message unnecessarily. For custom revert reasons use {tryGet}./ | function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(
uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))
);
}
| 7,135,115 | [
1,
8650,
487,
288,
588,
5779,
598,
279,
1679,
555,
883,
1347,
1375,
856,
68,
353,
486,
316,
326,
852,
18,
6425,
13269,
30,
1220,
445,
353,
6849,
2724,
518,
4991,
4767,
1776,
3778,
364,
326,
555,
883,
16209,
21513,
18,
2457,
1679,
15226,
14000,
999,
288,
698,
967,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
12,
203,
3639,
7320,
774,
1887,
863,
2502,
852,
16,
203,
3639,
2254,
5034,
498,
16,
203,
3639,
533,
3778,
9324,
203,
565,
262,
2713,
1476,
1135,
261,
2867,
13,
288,
203,
3639,
327,
203,
3639,
1758,
12,
203,
5411,
2254,
16874,
12,
11890,
5034,
24899,
588,
12,
1458,
6315,
7872,
16,
1731,
1578,
12,
856,
3631,
9324,
20349,
203,
3639,
11272,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
library SafeMath {
function ADD802(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function ADD802(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function SUB29(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB29(a, b, "SafeMath: subtraction underflow");
}
function SUB29(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL631(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function MUL631(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function DIV549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV549(a, b, "SafeMath: division by zero");
}
function DIV549(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD667(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD667(a, b, "SafeMath: modulo by zero");
}
function MOD667(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface IKeep2r {
function ADDVOTES925(address voter, uint amount) external; //inject NONSTANDARD NAMING
function REMOVEVOTES795(address voter, uint amount) external; //inject NONSTANDARD NAMING
function ADDKPRCREDIT324(address job, uint amount) external; //inject NONSTANDARD NAMING
function APPROVELIQUIDITY19(address liquidity) external; //inject NONSTANDARD NAMING
function REVOKELIQUIDITY95(address liquidity) external; //inject NONSTANDARD NAMING
function ADDJOB704(address job) external; //inject NONSTANDARD NAMING
function REMOVEJOB261(address job) external; //inject NONSTANDARD NAMING
function SETKEEP2RHELPER717(address _kprh) external; //inject NONSTANDARD NAMING
function SETGOVERNANCE887(address _governance) external; //inject NONSTANDARD NAMING
function ACCEPTGOVERNANCE419() external; //inject NONSTANDARD NAMING
function DISPUTE17(address keeper) external; //inject NONSTANDARD NAMING
function SLASH754(address bonded, address keeper, uint amount) external; //inject NONSTANDARD NAMING
function REVOKE96(address keeper) external; //inject NONSTANDARD NAMING
function RESOLVE192(address keeper) external; //inject NONSTANDARD NAMING
function GETPRIORVOTES700(address account, uint blockNumber) external view returns (uint); //inject NONSTANDARD NAMING
function TOTALBONDED836() external view returns (uint); //inject NONSTANDARD NAMING
}
contract Governance {
using SafeMath for uint;
string public constant name820 = "Governance"; //inject NONSTANDARD NAMING
uint public _quorumVotes = 5000; // % of total supply required
uint public _proposalThreshold = 5000;
uint public constant base706 = 10000; //inject NONSTANDARD NAMING
function SETQUORUM684(uint quorum_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Governance::setQuorum: timelock only");
require(quorum_ <= base706, "Governance::setQuorum: quorum_ > BASE");
_quorumVotes = quorum_;
}
function QUORUMVOTES610() public view returns (uint) { //inject NONSTANDARD NAMING
return KPR.TOTALBONDED836().MUL631(_quorumVotes).DIV549(base706);
}
function PROPOSALTHRESHOLD741() public view returns (uint) { //inject NONSTANDARD NAMING
return KPR.TOTALBONDED836().MUL631(_proposalThreshold).DIV549(base706);
}
function SETTHRESHOLD755(uint threshold_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Governance::setQuorum: timelock only");
require(threshold_ <= base706, "Governance::setThreshold: threshold_ > BASE");
_proposalThreshold = threshold_;
}
function PROPOSALMAXOPERATIONS305() public pure returns (uint) { return 10; } // 10 actions //inject NONSTANDARD NAMING
function VOTINGDELAY891() public pure returns (uint) { return 1; } // 1 block //inject NONSTANDARD NAMING
function VOTINGPERIOD297() public pure returns (uint) { return 40_320; } // ~7 days in blocks (assuming 15s blocks) //inject NONSTANDARD NAMING
IKeep2r immutable public KPR;
uint public proposalCount;
struct Proposal {
uint id;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
mapping (address => Receipt) receipts;
}
struct Receipt {
bool hasVoted;
bool support;
uint votes;
}
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
mapping (uint => Proposal) public proposals;
mapping (address => uint) public latestProposalIds;
bytes32 public constant domain_typehash397 = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); //inject NONSTANDARD NAMING
bytes32 public immutable DOMAINSEPARATOR;
bytes32 public constant ballot_typehash182 = keccak256("Ballot(uint256 proposalId,bool support)"); //inject NONSTANDARD NAMING
event PROPOSALCREATED434(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); //inject NONSTANDARD NAMING
event VOTECAST909(address voter, uint proposalId, bool support, uint votes); //inject NONSTANDARD NAMING
event PROPOSALCANCELED450(uint id); //inject NONSTANDARD NAMING
event PROPOSALQUEUED490(uint id, uint eta); //inject NONSTANDARD NAMING
event PROPOSALEXECUTED781(uint id); //inject NONSTANDARD NAMING
function PROPOSEJOB470(address job) public { //inject NONSTANDARD NAMING
require(msg.sender == address(KPR), "Governance::proposeJob: only VOTER can propose new jobs");
address[] memory targets;
targets[0] = address(KPR);
string[] memory signatures;
signatures[0] = "addJob(address)";
bytes[] memory calldatas;
calldatas[0] = abi.encode(job);
uint[] memory values;
values[0] = 0;
_PROPOSE700(targets, values, signatures, calldatas, string(abi.encodePacked("Governance::proposeJob(): ", job)));
}
function PROPOSE926(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { //inject NONSTANDARD NAMING
require(KPR.GETPRIORVOTES700(msg.sender, block.number.SUB29(1)) >= PROPOSALTHRESHOLD741(), "Governance::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "Governance::propose: proposal function information arity mismatch");
require(targets.length != 0, "Governance::propose: must provide actions");
require(targets.length <= PROPOSALMAXOPERATIONS305(), "Governance::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = STATE767(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "Governance::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "Governance::propose: one live proposal per proposer, found an already pending proposal");
}
return _PROPOSE700(targets, values, signatures, calldatas, description);
}
function _PROPOSE700(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) internal returns (uint) { //inject NONSTANDARD NAMING
uint startBlock = block.number.ADD802(VOTINGDELAY891());
uint endBlock = startBlock.ADD802(VOTINGPERIOD297());
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit PROPOSALCREATED434(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function QUEUE934(uint proposalId) public { //inject NONSTANDARD NAMING
require(STATE767(proposalId) == ProposalState.Succeeded, "Governance::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = block.timestamp.ADD802(delay);
for (uint i = 0; i < proposal.targets.length; i++) {
_QUEUEORREVERT932(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit PROPOSALQUEUED490(proposalId, eta);
}
function _QUEUEORREVERT932(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING
require(!queuedTransactions[keccak256(abi.encode(target, value, signature, data, eta))], "Governance::_queueOrRevert: proposal action already queued at eta");
_QUEUETRANSACTION380(target, value, signature, data, eta);
}
function EXECUTE292(uint proposalId) public payable { //inject NONSTANDARD NAMING
require(guardian == address(0x0) || msg.sender == guardian, "Governance:execute: !guardian");
require(STATE767(proposalId) == ProposalState.Queued, "Governance::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
_EXECUTETRANSACTION42(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit PROPOSALEXECUTED781(proposalId);
}
function CANCEL285(uint proposalId) public { //inject NONSTANDARD NAMING
ProposalState state = STATE767(proposalId);
require(state != ProposalState.Executed, "Governance::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(proposal.proposer != address(KPR) &&
KPR.GETPRIORVOTES700(proposal.proposer, block.number.SUB29(1)) < PROPOSALTHRESHOLD741(), "Governance::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
_CANCELTRANSACTION608(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit PROPOSALCANCELED450(proposalId);
}
function GETACTIONS567(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { //inject NONSTANDARD NAMING
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function GETRECEIPT636(uint proposalId, address voter) public view returns (Receipt memory) { //inject NONSTANDARD NAMING
return proposals[proposalId].receipts[voter];
}
function STATE767(uint proposalId) public view returns (ProposalState) { //inject NONSTANDARD NAMING
require(proposalCount >= proposalId && proposalId > 0, "Governance::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes.ADD802(proposal.againstVotes) < QUORUMVOTES610()) {
return ProposalState.Defeated;
} else if (proposal.forVotes <= proposal.againstVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= proposal.eta.ADD802(grace_period471)) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function CASTVOTE458(uint proposalId, bool support) public { //inject NONSTANDARD NAMING
_CASTVOTE871(msg.sender, proposalId, support);
}
function CASTVOTEBYSIG199(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { //inject NONSTANDARD NAMING
bytes32 structHash = keccak256(abi.encode(ballot_typehash182, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Governance::castVoteBySig: invalid signature");
_CASTVOTE871(signatory, proposalId, support);
}
function _CASTVOTE871(address voter, uint proposalId, bool support) internal { //inject NONSTANDARD NAMING
require(STATE767(proposalId) == ProposalState.Active, "Governance::_castVote: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "Governance::_castVote: voter already voted");
uint votes = KPR.GETPRIORVOTES700(voter, proposal.startBlock);
if (support) {
proposal.forVotes = proposal.forVotes.ADD802(votes);
} else {
proposal.againstVotes = proposal.againstVotes.ADD802(votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VOTECAST909(voter, proposalId, support, votes);
}
function GETCHAINID291() internal pure returns (uint) { //inject NONSTANDARD NAMING
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
event NEWDELAY307(uint indexed newDelay); //inject NONSTANDARD NAMING
event CANCELTRANSACTION220(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
event EXECUTETRANSACTION925(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
event QUEUETRANSACTION307(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); //inject NONSTANDARD NAMING
uint public constant grace_period471 = 14 days; //inject NONSTANDARD NAMING
uint public constant minimum_delay353 = 1 days; //inject NONSTANDARD NAMING
uint public constant maximum_delay422 = 30 days; //inject NONSTANDARD NAMING
uint public delay = minimum_delay353;
address public guardian;
address public pendingGuardian;
function SETGUARDIAN20(address _guardian) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setGuardian: !guardian");
pendingGuardian = _guardian;
}
function ACCEPTGUARDIANSHIP599() external { //inject NONSTANDARD NAMING
require(msg.sender == pendingGuardian, "Keep2rGovernance::setGuardian: !pendingGuardian");
guardian = pendingGuardian;
}
function ADDVOTES925(address voter, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addVotes: !guardian");
KPR.ADDVOTES925(voter, amount);
}
function REMOVEVOTES795(address voter, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::removeVotes: !guardian");
KPR.REMOVEVOTES795(voter, amount);
}
function ADDKPRCREDIT324(address job, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addKPRCredit: !guardian");
KPR.ADDKPRCREDIT324(job, amount);
}
function APPROVELIQUIDITY19(address liquidity) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::approveLiquidity: !guardian");
KPR.APPROVELIQUIDITY19(liquidity);
}
function REVOKELIQUIDITY95(address liquidity) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::revokeLiquidity: !guardian");
KPR.REVOKELIQUIDITY95(liquidity);
}
function ADDJOB704(address job) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::addJob: !guardian");
KPR.ADDJOB704(job);
}
function REMOVEJOB261(address job) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::removeJob: !guardian");
KPR.REMOVEJOB261(job);
}
function SETKEEP2RHELPER717(address kprh) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setKeep2rHelper: !guardian");
KPR.SETKEEP2RHELPER717(kprh);
}
function SETGOVERNANCE887(address _governance) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::setGovernance: !guardian");
KPR.SETGOVERNANCE887(_governance);
}
function ACCEPTGOVERNANCE419() external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::acceptGovernance: !guardian");
KPR.ACCEPTGOVERNANCE419();
}
function DISPUTE17(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::dispute: !guardian");
KPR.DISPUTE17(keeper);
}
function SLASH754(address bonded, address keeper, uint amount) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::slash: !guardian");
KPR.SLASH754(bonded, keeper, amount);
}
function REVOKE96(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::revoke: !guardian");
KPR.REVOKE96(keeper);
}
function RESOLVE192(address keeper) external { //inject NONSTANDARD NAMING
require(msg.sender == guardian, "Keep2rGovernance::resolve: !guardian");
KPR.RESOLVE192(keeper);
}
mapping (bytes32 => bool) public queuedTransactions;
constructor(address token_) public {
guardian = msg.sender;
KPR = IKeep2r(token_);
DOMAINSEPARATOR = keccak256(abi.encode(domain_typehash397, keccak256(bytes(name820)), GETCHAINID291(), address(this)));
}
receive() external payable { }
function SETDELAY397(uint delay_) public { //inject NONSTANDARD NAMING
require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock.");
require(delay_ >= minimum_delay353, "Timelock::setDelay: Delay must exceed minimum delay.");
require(delay_ <= maximum_delay422, "Timelock::setDelay: Delay must not exceed maximum delay.");
delay = delay_;
emit NEWDELAY307(delay);
}
function _QUEUETRANSACTION380(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes32) { //inject NONSTANDARD NAMING
require(eta >= GETBLOCKTIMESTAMP893().ADD802(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay.");
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = true;
emit QUEUETRANSACTION307(txHash, target, value, signature, data, eta);
return txHash;
}
function _CANCELTRANSACTION608(address target, uint value, string memory signature, bytes memory data, uint eta) internal { //inject NONSTANDARD NAMING
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
queuedTransactions[txHash] = false;
emit CANCELTRANSACTION220(txHash, target, value, signature, data, eta);
}
function _EXECUTETRANSACTION42(address target, uint value, string memory signature, bytes memory data, uint eta) internal returns (bytes memory) { //inject NONSTANDARD NAMING
bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta));
require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued.");
require(GETBLOCKTIMESTAMP893() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock.");
require(GETBLOCKTIMESTAMP893() <= eta.ADD802(grace_period471), "Timelock::executeTransaction: Transaction is stale.");
queuedTransactions[txHash] = false;
bytes memory callData;
if (bytes(signature).length == 0) {
callData = data;
} else {
callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data);
}
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value:value}(callData);
require(success, "Timelock::executeTransaction: Transaction execution reverted.");
emit EXECUTETRANSACTION925(txHash, target, value, signature, data, eta);
return returnData;
}
function GETBLOCKTIMESTAMP893() internal view returns (uint) { //inject NONSTANDARD NAMING
// solium-disable-next-line security/no-block-members
return block.timestamp;
}
} | inject NONSTANDARD NAMING
| function REMOVEJOB261(address job) external; | 12,851,096 | [
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,
26056,
18321,
5558,
21,
12,
2867,
1719,
13,
3903,
31,
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
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary/blob/master/contracts/BokkyPooBahsDateTimeLibrary.sol";
contract RussianRoulette is ERC20, Ownable {
modifier lockSwap {
_inSwap = true;
_;
_inSwap = false;
}
modifier liquidityAdd {
_inLiquidityAdd = true;
_;
_inLiquidityAdd = false;
}
uint256 internal _maxTransfer = 2;//if LP is 0.05 then 1% is even more negligible increase maxTransfer to 4
uint256 internal _buyRate1 = 15;
uint256 internal _buyRate2 = 10;
uint256 public _sellRate1 = 90;
uint256 internal _sellRate2 = 15;
uint256 internal _rrwinnerRate = 10;
uint256 internal _reflectRate = 5;
uint256 internal _cooldown = 60 seconds;
uint256 internal _rrcooldown = 0 seconds;
uint256 internal _swapFeesAt = 1000 ether;
bool internal _useSecondFees = false;
bool internal _useWinnerFees = false;
bool internal _swapFees = true;
uint public odds = 3; //3 here, 2 front end
uint256 internal _ethReflectionBasis;
uint256 internal _totalReflected;
uint256 internal _totalMarketing;
uint256 internal _totalDelegated;
uint256 internal _totalEthReflectedToDate;
uint256 internal _totalEthRBWToDate;
uint256 internal _totalTaxesToDate;
address payable internal _marketingWallet;
address payable internal _treasuryWallet;
uint256 internal _totalSupply = 0;
uint256 internal _totalBurnt = 0;
bool internal _teamMint = false;
IUniswapV2Router02 internal _router = IUniswapV2Router02(address(0));
address internal _pair;
bool internal _inSwap = false;
bool internal _inLiquidityAdd = false;
bool internal _tradingActive = false;
uint256 internal _tradingStartBlock = 3041510;//mainnet 14400000
mapping(address => uint256) private _balances;
mapping(address => bool) private _reflectionExcluded;
mapping(address => bool) private _taxExcluded;
mapping(address => bool) private _rrwinners;
mapping(address => bool) private _bot;
mapping(address => uint256) private _lastBuy;
mapping(address => uint256) private _lastPlay;
mapping(address => uint256) private _daysLeftToCool;
mapping(address => uint256) private _lastReflectionBasis;
mapping(address => uint256) private _sellDelegation;
address[] internal _reflectionExcludedList;
address[] public allWinners; // shows lifetime rr winners
constructor(
address uniswapFactory,
address uniswapRouter,
address payable treasuryWallet
) ERC20("Wutang Clan", "WUSUN") Ownable() {
addTaxExcluded(owner());
addTaxExcluded(treasuryWallet);
addTaxExcluded(address(this));
_marketingWallet = payable(owner());
_treasuryWallet = treasuryWallet;
_router = IUniswapV2Router02(uniswapRouter);
IUniswapV2Factory uniswapContract = IUniswapV2Factory(uniswapFactory);
_pair = uniswapContract.createPair(address(this), _router.WETH());
}
function addLiquidity(uint256 tokens) public payable onlyOwner() liquidityAdd {
_mint(address(this), tokens);
_approve(address(this), address(_router), tokens);
_router.addLiquidityETH{value: msg.value}(
address(this),
tokens,
0,
0,
owner(),
//consider not relying on blocktime
block.timestamp
);
if (!_tradingActive) {
_tradingActive = true;//once we add liquidity we activate trading
//_tradingStartBlock = block.number;
}
}
//Manually increase amount available for claiming if we sent ETH from external wallet to our contract
function addReflectionETH(uint256 amount) public onlyOwner() {
_ethReflectionBasis += amount;
}
function EthReflectionBasis() public view returns (uint256) {
return _ethReflectionBasis;
}
function delegatedForSell() public view returns (uint256) {
uint256 tokensDelegated = _sellDelegation[msg.sender];
return tokensDelegated;
}
function lastReflectionBasis(address account) public view returns (uint256) {
return _lastReflectionBasis[account];
}
function currentRewardForWallet(address addr) public view returns(uint256) {
uint256 basisDifference = _ethReflectionBasis - _lastReflectionBasis[addr];//even if you dont claim your eth will be there on contract waiting
uint256 owed = basisDifference * balanceOf(addr) / _totalSupply;
return owed;
}
function totalEthReflectedToDate() public view returns (uint256) {
return _totalEthReflectedToDate;
}
function totalEthRebalancingToDate() public view returns (uint256) {
return _totalEthRBWToDate;
}
function totalEthTaxedToDate() public view returns (uint256) {
return _totalTaxesToDate;
}
function totalBurnt() public view returns (uint256) {
return _totalBurnt;
}
function maxTransferAllowed() public view returns (uint256) {
uint256 maxTxAmount = totalSupply() * _maxTransfer / 100;
return maxTxAmount;
}
function tradingStartBlock() public view returns (uint256) {
return _tradingStartBlock;
}
function secondFeesActive() public view returns (bool) {
return _useSecondFees;
}
function winnerFeesActive() public view returns (bool) {
return _useWinnerFees;
}
function whatsTodayDate() public view returns (uint) {
uint date = isTodayFirstDayOfMonth();
return date;
}
function RussianRouletteDay() public view returns (bool) {
uint date = isTodayFirstDayOfMonth();
if(date != 1){
return false;
}
return true;
}
function RussianRouletteEligible(address account) public view returns (bool) {
return _taxExcluded[account];
}
// check if eligible for reflections
function isReflectionExcluded(address account) public view returns (bool) {
return _reflectionExcluded[account];
}
//remove eligibility from reflections
function removeReflectionExcluded(address account) public onlyOwner() {
require(isReflectionExcluded(account), "Account must be excluded");
_reflectionExcluded[account] = false;
}
function addReflectionExcluded(address account) public onlyOwner() {
_addReflectionExcluded(account);
}
function _addReflectionExcluded(address account) internal {
require(!isReflectionExcluded(account), "Account must not be excluded");
_reflectionExcluded[account] = true;
}
//................................................................
// Tax checking functions........................................
function isTaxExcluded(address account) public view returns (bool) {
return _taxExcluded[account];
}
// adds address to tax exclusion
function addTaxExcluded(address account) public onlyOwner() {//onlyowner
require(!isTaxExcluded(account), "Account must not be excluded");
_taxExcluded[account] = true;
}
function removeTaxExcluded(address account) public onlyOwner() {
require(isTaxExcluded(account), "Account must not be excluded");
_taxExcluded[account] = false;
}
// The Russian Roulette Play
function addrrwinners(address account) internal{
require(!isTaxExcluded(account), "Account must not be excluded");
_taxExcluded[account] = true;
allWinners.push(account);
}
function setOdds(uint8 _odds) public onlyOwner() { //odds can be set manual and remain same or by owner
assert( _odds > 0 && _odds <= 3);
odds = _odds;
}
function setSellTax(uint8 rate) public onlyOwner() {
assert( _sellRate1 > 0);
_sellRate1 = rate;
}
function random(uint _rollsize) internal view returns(uint) {
return uint(keccak256(abi.encodePacked(block.difficulty, block.timestamp, _rollsize)));
}
// Play Russian Roulette - spin cylinder with combined odds of 1 in 6
function _playRussianRoulette(uint _num) public {
require( balanceOf(msg.sender) > 100000000000000000000, "Should hold at least 100 tokens"); //check if token holder
require( _num > 0 && _num <= odds, "Enter a value within the odds range");
uint daysSincePlay = daysDifference();
require((daysSincePlay - _daysLeftToCool[msg.sender]) >= 0,"Wait for the new month to play");//since wallet last played, month has reset
uint result = random(_num) % odds;
if(result == _num){
addrrwinners(msg.sender);
}
//set last play time & days till month is over
_daysLeftToCool[msg.sender] = daysLeftInMonth();//uint 1-30
_lastPlay[msg.sender] = block.timestamp;//(then - last) > cooldownDays | in days
return;
}
//...................................................
//bot accounts on uniswap trading from router
function isBot(address account) public view returns (bool) {
return _bot[account];
}
function addBot(address account) internal {
_addBot(account);
}
function _addBot(address account) internal {
require(!isBot(account), "Account must not be flagged");
require(account != address(_router), "Account must not be uniswap router");
require(account != _pair, "Account must not be uniswap pair");
_bot[account] = true;
_addReflectionExcluded(account);
}
function removeBot(address account) public onlyOwner() {
require(isBot(account), "Account must be flagged");
_bot[account] = false;
removeReflectionExcluded(account);
}
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return _balances[account];
}
function _addBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] + amount;
}
function _subtractBalance(address account, uint256 amount) internal {
_balances[account] = _balances[account] - amount;
}
//--------------------------------------------------------------------------------------------------------------------
//function to transfer money within token overwrites erc-20 method
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (isTaxExcluded(sender) || isTaxExcluded(recipient)) {//exclude contract transfers too
_rawTransferFree(sender, recipient, amount);
return;
}
uint256 currentblock = block.number;
require(currentblock >= _tradingStartBlock, "Trading starts at block 14400000");
require(!isBot(sender), "Sender locked as bot");
require(!isBot(recipient), "Recipient locked as bot");
uint256 maxTxAmount = totalSupply() * _maxTransfer / 100;//not % change it to 100 for actual % calc
require(amount <= maxTxAmount || _inLiquidityAdd || _inSwap || recipient == address(_router), "Exceeds max transaction amount");
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= _swapFeesAt;
if(contractTokenBalance >= maxTxAmount) {
contractTokenBalance = maxTxAmount;
}
if (
overMinTokenBalance &&
!_inSwap &&
sender != _pair &&
_swapFees
) {
_swap(contractTokenBalance);
}
_claimReflection(payable(sender));
_claimReflection(payable(recipient));
uint256 send = amount;
uint256 reflect;
uint256 marketing;
//indicates swap
bool tokenSwap = false;
if (sender == _pair && _tradingActive) {
// Buy, apply buy fee schedule
(
send,
reflect,
marketing
) = _getBuyTaxAmounts(amount);
require(block.timestamp - _lastBuy[tx.origin] > _cooldown || _inSwap, "hit cooldown, try again later");
_lastBuy[tx.origin] = block.timestamp;
//indicates swap
tokenSwap = true;
} else if (recipient == _pair && _tradingActive) {
// Sell, apply sell fee schedule
(
send,
reflect,
marketing
) = _getSellTaxAmounts(amount);
//indicates swap
tokenSwap = true;
}
if(tokenSwap == false){ //Wallet to Wallet transfer
if (sender == _treasuryWallet || recipient == _treasuryWallet) {
_rawTransfer(sender, recipient, send);
return;
}else{//ordinary wallet - disable wallet to wallet transfer to avoid cheating on RR play
( send,
reflect,
marketing
) = _getTransferTaxAmounts(amount);
//reset
tokenSwap = false;
}
}
_rawTransfer(sender, recipient, send);
if(marketing>0){_takeMarketing(sender, marketing);}
if(reflect>0){_reflect(sender, reflect);}
if (_tradingActive && block.number == _tradingStartBlock && !isTaxExcluded(tx.origin)) {
if (tx.origin == address(_pair)) {
if (sender == address(_pair)) {
_addBot(recipient);
} else {
_addBot(sender);
}
} else {
_addBot(tx.origin);
}
}
}
function _claimReflection(address payable addr) internal {
if (addr == _pair || addr == address(_router)) return;
uint256 basisDifference = _ethReflectionBasis - _lastReflectionBasis[addr];//even if you dont claim your eth will be there on contract waiting
uint256 owed = basisDifference * balanceOf(addr) / _totalSupply;
_lastReflectionBasis[addr] = _ethReflectionBasis;
if (owed == 0) {
return;
}
addr.transfer(owed);
}
function claimReflection() public {
_claimReflection(payable(msg.sender));
}
function _rawTransferFree(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "reflect from the zero address");
uint musi = isTodayFirstDayOfMonth();
if(musi == 1){_useWinnerFees = true;}
if(_inLiquidityAdd || sender == address(this) || sender == _treasuryWallet || recipient == _treasuryWallet || sender == _marketingWallet || recipient == _marketingWallet){//No fees
_rawTransfer(sender, recipient, amount);
}else{//treasury & marketing arent taxed
uint256 send = amount;
uint256 reflect;
uint256 marketing;
//indicates swap
bool tokenSwap = false;
if (sender == _pair && _tradingActive) {// Buy, apply buy fee schedule
(send,reflect,marketing) = _getBuyTaxAmounts(amount);
tokenSwap = true;//indicates swap
} else if (recipient == _pair && _tradingActive) {// Sell, apply sell fee schedule
(send,reflect,marketing) = _getWinnerTaxAmounts(amount);
tokenSwap = true;//indicates swap
}
if(tokenSwap == false){ //Wallet to Wallet transfer
if(_inLiquidityAdd || sender == _treasuryWallet || recipient == _treasuryWallet || sender == _marketingWallet || recipient == _marketingWallet){//No fees
_rawTransfer(sender, recipient, send);
return;
}else{//ordinary wallet - disable wallet to wallet transfer to avoid cheating on RR play
(send,reflect,marketing) = _getTransferTaxAmounts(amount);
tokenSwap = false;//reset
}
}
_rawTransfer(sender, recipient, send);
if(marketing>0){_takeMarketing(sender, marketing);}
if(reflect>0){_reflect(sender, reflect);}
}
}
function _swap(uint256 amount) internal lockSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _router.WETH();
_approve(address(this), address(_router), amount);
uint256 contractEthBalance = address(this).balance;
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amount,//amount in
0,//amount out in tokens
path,//call path
address(this),//address to
block.timestamp//deadline
);
uint256 tradeValue = address(this).balance - contractEthBalance;//new balance less the old balance
uint256 marketingAmount = amount * _totalMarketing / (_totalMarketing + _totalReflected);
uint256 reflectedAmount = amount - marketingAmount;
uint256 marketingEth = tradeValue * _totalMarketing / (_totalMarketing + _totalReflected);
uint256 reflectedEth = tradeValue - marketingEth;
if (marketingEth > 0) {
//total taxes on contract = total tokens on contract
//totalMarketing/totalTaxes = RBW share
_marketingWallet.transfer(marketingEth);//only transfer RBW amount and leave reflections eth on contract
//should add some eth to contract for gas in case all the eth there was from swapAll() then we wont have gas to send balance
}
_totalMarketing -= marketingAmount;//collected in tokens using it only to track how much is due to be assigned to RBW
_totalReflected -= reflectedAmount;//same, tracks whats due to be converted into ETH for reflections
_ethReflectionBasis += reflectedEth;//notifies users claim request how much is available for claiming
_totalEthReflectedToDate += reflectedEth; //Total ETH reflected ever
_totalEthRBWToDate += marketingEth;//Total ETH to RBW ever
_totalTaxesToDate += tradeValue; //Total taxes collected ever in ETH
}
function swapAll() public {//everyone is free to declare reflections
uint256 maxTxAmount = totalSupply() * _maxTransfer / 100;//make it a percentage
uint256 contractSwapAllowance = _totalMarketing + _totalReflected;//current taxes collected on contract in tokens
if(contractSwapAllowance >= maxTxAmount)
{
contractSwapAllowance = maxTxAmount;
}
if (
!_inSwap
) {
_swap(contractSwapAllowance);
}
}
function _swapSellForWallet(address payable addr, uint256 amount) internal lockSwap {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _router.WETH();
//we should leave proceeds in LP & take 10% only ideally, then cover the 10% from buy tax and sharebidding
//share bidding allows you to sell without affecting the LP but we charge 10% for every proxy service to both parties netting 20% (10% seller tokens & 10% buyer ETH)
//Lastly we rely on investors to also buy the small dips and help level out the chart
uint256 amountBurnt = (amount * _sellRate1) / 100;
uint256 amountSwap = amount - amountBurnt;
_burnTokens(amountBurnt);
_approve(address(this), address(_router), amountSwap);
//Leaving comments to explore capabilities of swap functions & how you want your transactions to appear: broker capabilities need to be explored in escrow
//uint256 contractEthBalance = address(this).balance;
// uint256 gasBefore = gasleft();//gas
_router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountSwap,//amount in
0,//amount out in tokens
path,//call path
addr,//address to
block.timestamp//deadline
);
//uint256 tradeValue = address(this).balance - contractEthBalance;//new balance less the old balance
/*uint256 gasAfter = gasleft();//gas
uint256 gasUsed = gasBefore - gasAfter;
uint256 gasRefund = gasUsed * tx.gasprice; //10% extra to cover eth transfer to seller
uint256 extraFee = gasRefund * 1/10;
uint256 userProceeds = tradeValue - gasRefund - extraFee;
//Had to change eth being send to contarct first, realised it will cause sell trades to not appear properly
//ETH is being send directly to wallet of owner, no need to calculate how much to transfer
if (tradeValue > 0) {
addr.transfer(tradeValue);//seller gets ETH
}
*/
_sellDelegation[msg.sender] -= amount;
}
function swapForUser() public {//sell through contract to be taxed correctly, bypassing Uniswap tax limitations
require(_sellDelegation[msg.sender] > 0, "no tokens delegated for selling");
uint256 maxTxAmount = totalSupply() * _maxTransfer / 100;//make it a percentage
uint256 walletTokenBalance = _sellDelegation[msg.sender];//users balance of delegated tokens
if(walletTokenBalance >= maxTxAmount)
{
walletTokenBalance = maxTxAmount;
}
if (
!_inSwap
) {
_swapSellForWallet(payable(msg.sender), walletTokenBalance);
}
}
function withdrawAll() public onlyOwner() {
uint256 totalETH = address(this).balance;
_marketingWallet.transfer(totalETH);//moves all ETH from contract if we migrate
}
function _burnTokens(uint256 amount) internal {
//burn 90% and leave 10% -- update delegated mapping for wallet as well in swapForUser
_totalSupply -= amount;//update supply
address burnAddr = 0x000000000000000000000000000000000000dEaD;
_rawTransfer(address(this), burnAddr, amount);//contract & burn addy balances updated in here, no need to update again
_totalBurnt += amount;
//emit Transfer(address(this), burnAddr, amount);
}
function _reflect(address account, uint256 amount) internal {
require(account != address(0), "reflect from the zero address");
_rawTransfer(account, address(this), amount);
_totalReflected += amount;//keep track of reflection amounts since all taxes are collected to contract address
//emit Transfer(account, address(this), amount);
}
function _takeMarketing(address account, uint256 amount) internal {
require(account != address(0), "take marketing from the zero address");
_rawTransfer(account, address(this), amount);
_totalMarketing += amount;//keep track like above, we need a way to know how to split the ETH after swapAll()
//emit Transfer(account, address(this), amount);
}
function _delegateSell(uint256 amount) public {
require(msg.sender != address(0), "delegate from the zero address");
//using mapping to keep track of all tokens delegated to contract for sell
_sellDelegation[msg.sender] += amount;//for each wallet..only change back to zero when you sell
_rawTransfer(msg.sender, address(this), amount);
_totalDelegated += amount;//keep track of all tokens delegated to contract for selling
//emit Transfer(msg.sender, address(this), amount);
}
function _getTransferTaxAmounts(uint256 amount)
internal
pure
returns (
uint256 send,
uint256 reflect,
uint256 marketing
)
{
reflect = 0;
send = (amount * 50) / 100;
marketing = amount - send;
assert(marketing >= 0);
assert(send + reflect + marketing == amount);
}
function _getBuyTaxAmounts(uint256 amount)
internal
view
returns (
uint256 send,
uint256 reflect,
uint256 marketing
)
{
marketing = 0;
reflect = 0;
if (_useSecondFees) {
uint256 sendRate = 100 - _reflectRate;
assert(sendRate >= 0);
send = (amount * sendRate) / 100;
reflect = amount - send;
assert(reflect >= 0);
assert(send + reflect + marketing == amount);
} else {
uint256 sendRate = 100 - _buyRate1;
assert(sendRate >= 0);
send = (amount * sendRate) / 100; //send 85%
reflect = (amount * _reflectRate) / 100; //take 5% reflection
marketing = amount - send - reflect; //10% thats left goes to RBW
assert(reflect >= 0);
assert(send + reflect + marketing == amount);
}
}
function _getSellTaxAmounts(uint256 amount)
internal
view
returns (
uint256 send,
uint256 reflect,
uint256 marketing
)
{
marketing = 0;
reflect = 0;
//Check if RRday first
if (_useSecondFees) {
uint256 sendRate = 100 - _sellRate2;
assert(sendRate >= 0);
send = (amount * sendRate) / 100;
marketing = amount - send;
assert(reflect >= 0);
assert(send + reflect + marketing == amount);
} else {
uint256 sendRate = 100 - _sellRate1;
assert(sendRate >= 0);
send = (amount * sendRate) / 100;
marketing = amount - send;
assert(reflect >= 0);
assert(send + reflect + marketing == amount);
}
}
function _getWinnerTaxAmounts(uint256 amount)
internal
view
returns (
uint256 send,
uint256 reflect,
uint256 marketing
)
{
marketing = 0;
reflect = 0;
//Check if RRday first
if ((_useWinnerFees) ) {
uint256 sendRate = 100 - _rrwinnerRate;
send = (amount * sendRate) / 100;
assert(send + reflect + marketing == amount);
} else {
uint256 sendRate = 100 - _sellRate1;
assert(sendRate >= 0);
send = (amount * sendRate) / 100;
marketing = amount - send;
assert(send + reflect + marketing == amount);
}
}
// modified from OpenZeppelin ERC20
function _rawTransfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "transfer from the zero address");
require(recipient != address(0), "transfer to the zero address");
uint256 senderBalance = balanceOf(sender);
require(senderBalance >= amount, "transfer amount exceeds balance");
unchecked {
_subtractBalance(sender, amount);
}
_addBalance(recipient, amount);
emit Transfer(sender, recipient, amount);
}
function setMaxTransfer(uint256 maxTransfer) public onlyOwner() {
_maxTransfer = maxTransfer;
}
function setSwapFees(bool swapFees) public onlyOwner() {
_swapFees = swapFees;
}
function setUseSecondFees(bool useSecondFees) public onlyOwner() {
_useSecondFees = useSecondFees;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function _mint(address account, uint256 amount) internal override {
_totalSupply += amount;
_addBalance(account, amount);
emit Transfer(address(0), account, amount);
}
function mintTeam(uint256 amount) public onlyOwner() {
require(_teamMint == false, "Team tokens already minted");
_mint(_marketingWallet, amount);
_teamMint = true;
}
function airdrop(address[] memory accounts, uint256[] memory amounts) public onlyOwner() {
require(accounts.length == amounts.length, "array lengths must match");
for (uint256 i = 0; i < accounts.length; i++) {
_mint(accounts[i], amounts[i]);
}
}
function tradingStarted() internal view returns (bool) {
if (_tradingStartBlock < block.number){
return true;
}else{
return false;
}
}
// date checks
function daysDifference() public view returns (uint){
uint daysLeft = BokkyPooBahsDateTimeLibrary.diffDays(_lastPlay[msg.sender], block.timestamp);//then - now
return daysLeft;
}
function daysLeftInMonth() public view returns (uint){
uint daysTotal = BokkyPooBahsDateTimeLibrary.getDaysInMonth(block.timestamp);
uint daysInto = isTodayFirstDayOfMonth();
uint daysLeft = daysTotal - daysInto;
return daysLeft;
}
function isTodayFirstDayOfMonth() internal view returns (uint) { // to be made internal
uint today = BokkyPooBahsDateTimeLibrary.getDay(block.timestamp);
return today;
}
receive() external payable {}
}
| not % change it to 100 for actual % calc
| uint256 maxTxAmount = totalSupply() * _maxTransfer / 100; | 6,355,182 | [
1,
902,
738,
2549,
518,
358,
2130,
364,
3214,
738,
7029,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
943,
4188,
6275,
273,
2078,
3088,
1283,
1435,
380,
389,
1896,
5912,
342,
2130,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
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);
}
/**
* @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 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 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 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());
}
}
contract DaoStakeContract is Ownable, Pausable {
// Library for safely handling uint256
using SafeMath for uint256;
uint256 ONE_DAY;
uint256 public stakeDays;
uint256 public maxStakedQuantity;
address public phnxContractAddress;
uint256 public ratio;
uint256 public totalStakedTokens;
mapping(address => uint256) public stakerBalance;
mapping(uint256 => StakerData) public stakerData;
struct StakerData {
uint256 altQuantity;
uint256 initiationTimestamp;
uint256 durationTimestamp;
uint256 rewardAmount;
address staker;
}
event StakeCompleted(
uint256 altQuantity,
uint256 initiationTimestamp,
uint256 durationTimestamp,
uint256 rewardAmount,
address staker,
address phnxContractAddress,
address portalAddress
);
event Unstake(
address staker,
address stakedToken,
address portalAddress,
uint256 altQuantity,
uint256 durationTimestamp
); // When ERC20s are withdrawn
event BaseInterestUpdated(uint256 _newRate, uint256 _oldRate);
constructor() public {
ratio = 821917808219178;
phnxContractAddress = 0x38A2fDc11f526Ddd5a607C1F251C065f40fBF2f7;
maxStakedQuantity = 10000000000000000000000;
stakeDays = 365;
ONE_DAY = 60;
}
/* @dev stake function which enable the user to stake PHNX Tokens.
* @param _altQuantity, PHNX amount to be staked.
* @param _days, how many days PHNX tokens are staked for (in days)
*/
function stakeALT(uint256 _altQuantity, uint256 _days)
public
whenNotPaused
returns (uint256 rewardAmount)
{
require(_days <= stakeDays && _days > 0, "Invalid Days"); // To check days
require(
_altQuantity <= maxStakedQuantity && _altQuantity > 0,
"Invalid PHNX quantity"
); // To verify PHNX quantity
IERC20(phnxContractAddress).transferFrom(
msg.sender,
address(this),
_altQuantity
);
rewardAmount = _calculateReward(_altQuantity, ratio, _days);
uint256 _timestamp = block.timestamp;
if (stakerData[_timestamp].staker != address(0)) {
_timestamp = _timestamp.add(1);
}
stakerData[_timestamp] = StakerData(
_altQuantity,
_timestamp,
_days.mul(ONE_DAY),
rewardAmount,
msg.sender
);
stakerBalance[msg.sender] = stakerBalance[msg.sender].add(_altQuantity);
totalStakedTokens = totalStakedTokens.add(_altQuantity);
IERC20(phnxContractAddress).transfer(msg.sender, rewardAmount);
emit StakeCompleted(
_altQuantity,
_timestamp,
_days.mul(ONE_DAY),
rewardAmount,
msg.sender,
phnxContractAddress,
address(this)
);
}
/* @dev unStake function which enable the user to withdraw his PHNX Tokens.
* @param _expiredTimestamps, time when PHNX tokens are unlocked.
* @param _amount, amount to be withdrawn by the user.
*/
function unstakeALT(uint256[] calldata _expiredTimestamps, uint256 _amount)
external
whenNotPaused
returns (uint256)
{
require(_amount > 0, "Amount should be greater than 0");
uint256 withdrawAmount = 0;
uint256 burnAmount = 0;
for (uint256 i = 0; i < _expiredTimestamps.length; i = i.add(1)) {
require(
stakerData[_expiredTimestamps[i]].durationTimestamp != 0,
"Nothing staked"
);
if (
_expiredTimestamps[i].add(
stakerData[_expiredTimestamps[i]].durationTimestamp //if timestamp is not expired
) >= block.timestamp
) {
uint256 _remainingDays = (
stakerData[_expiredTimestamps[i]]
.durationTimestamp
.add(_expiredTimestamps[i])
.sub(block.timestamp)
)
.div(ONE_DAY);
uint256 _totalDays = stakerData[_expiredTimestamps[i]]
.durationTimestamp
.div(ONE_DAY);
if (_amount >= stakerData[_expiredTimestamps[i]].altQuantity) {
uint256 stakeBurn = _calculateBurn(
stakerData[_expiredTimestamps[i]].altQuantity,
_remainingDays,
_totalDays
);
burnAmount = burnAmount.add(stakeBurn);
withdrawAmount = withdrawAmount.add(
stakerData[_expiredTimestamps[i]].altQuantity.sub(
stakeBurn
)
);
_amount = _amount.sub(
stakerData[_expiredTimestamps[i]].altQuantity
);
emit Unstake(
msg.sender,
phnxContractAddress,
address(this),
stakerData[_expiredTimestamps[i]].altQuantity,
_expiredTimestamps[i]
);
stakerData[_expiredTimestamps[i]].altQuantity = 0;
} else if (
(_amount < stakerData[_expiredTimestamps[i]].altQuantity) &&
_amount > 0 // if timestamp is expired
) {
stakerData[_expiredTimestamps[i]]
.altQuantity = stakerData[_expiredTimestamps[i]]
.altQuantity
.sub(_amount);
uint256 stakeBurn = _calculateBurn(
_amount,
_remainingDays,
_totalDays
);
burnAmount = burnAmount.add(stakeBurn);
withdrawAmount = withdrawAmount.add(_amount.sub(stakeBurn));
emit Unstake(
msg.sender,
phnxContractAddress,
address(this),
_amount,
_expiredTimestamps[i]
);
_amount = 0;
}
} else {
if (_amount >= stakerData[_expiredTimestamps[i]].altQuantity) {
_amount = _amount.sub(
stakerData[_expiredTimestamps[i]].altQuantity
);
withdrawAmount = withdrawAmount.add(
stakerData[_expiredTimestamps[i]].altQuantity
);
emit Unstake(
msg.sender,
phnxContractAddress,
address(this),
stakerData[_expiredTimestamps[i]].altQuantity,
_expiredTimestamps[i]
);
stakerData[_expiredTimestamps[i]].altQuantity = 0;
} else if (
(_amount < stakerData[_expiredTimestamps[i]].altQuantity) &&
_amount > 0
) {
stakerData[_expiredTimestamps[i]]
.altQuantity = stakerData[_expiredTimestamps[i]]
.altQuantity
.sub(_amount);
withdrawAmount = withdrawAmount.add(_amount);
emit Unstake(
msg.sender,
phnxContractAddress,
address(this),
_amount,
_expiredTimestamps[i]
);
break;
}
}
}
require(withdrawAmount != 0, "Not Transferred");
if (burnAmount > 0) {
IERC20(phnxContractAddress).transfer(
0x0000000000000000000000000000000000000001,
burnAmount
);
}
stakerBalance[msg.sender] = stakerBalance[msg.sender].sub(
withdrawAmount
);
totalStakedTokens = totalStakedTokens.sub(withdrawAmount);
IERC20(phnxContractAddress).transfer(msg.sender, withdrawAmount);
return withdrawAmount;
}
/* @dev to calculate reward Amount
* @param _altQuantity , amount of ALT tokens staked.
*@param _baseInterest rate
*/
function _calculateReward(
uint256 _altQuantity,
uint256 _ratio,
uint256 _days
) internal pure returns (uint256 rewardAmount) {
rewardAmount = (_altQuantity.mul(_ratio).mul(_days)).div(
1000000000000000000
);
}
/* @dev function to calculate the amount of PHNX token burned incase of early unstake.
*@param _amount, The amount of Tokens user is unstaking.
*@param _remainingDays, remaining time before the tokens will be unlocked.
*@param _totalDays, total days tokens were staked for.
*/
function _calculateBurn(
uint256 _amount,
uint256 _remainingDays,
uint256 _totalDays
) internal pure returns (uint256 burnAmount) {
burnAmount = ((_amount * _remainingDays) / _totalDays);
}
/* @dev to set base interest rate. Can only be called by owner
* @param _rate, interest rate (in wei)
*/
function updateRatio(uint256 _rate) public onlyOwner whenNotPaused {
ratio = _rate;
}
function updateTime(uint256 _time) public onlyOwner whenNotPaused {
ONE_DAY = _time;
}
function updateQuantity(uint256 _quantity) public onlyOwner whenNotPaused {
maxStakedQuantity = _quantity;
}
/* @dev function to update stakeDays.
*@param _stakeDays, updated Days .
*/
function updatestakeDays(uint256 _stakeDays) public onlyOwner {
stakeDays = _stakeDays;
}
/* @dev Funtion to withdraw all PHNX from contract incase of emergency, can only be called by owner.*/
function withdrawTokens() public onlyOwner {
IERC20(phnxContractAddress).transfer(
owner(),
IERC20(phnxContractAddress).balanceOf(address(this))
);
pause();
}
function getTotalrewardTokens() external view returns(uint256){
return IERC20(phnxContractAddress).balanceOf(address(this)).sub(totalStakedTokens);
}
/* @dev function to update Phoenix contract address.
*@param _address, new address of the contract.
*/
function setPheonixContractAddress(address _address) public onlyOwner {
phnxContractAddress = _address;
}
/* @dev function which restricts the user from stakng PHNX tokens. */
function pause() public onlyOwner {
_pause();
}
/* @dev function which disables the Pause function. */
function unPause() public onlyOwner {
_unpause();
}
} | @dev function to calculate the amount of PHNX token burned incase of early unstake.@param _amount, The amount of Tokens user is unstaking.@param _remainingDays, remaining time before the tokens will be unlocked.@param _totalDays, total days tokens were staked for./ | function _calculateBurn(
uint256 _amount,
uint256 _remainingDays,
uint256 _totalDays
) internal pure returns (uint256 burnAmount) {
burnAmount = ((_amount * _remainingDays) / _totalDays);
}
| 1,543,776 | [
1,
915,
358,
4604,
326,
3844,
434,
15490,
17106,
1147,
18305,
329,
316,
3593,
434,
11646,
640,
334,
911,
18,
389,
8949,
16,
1021,
3844,
434,
13899,
729,
353,
640,
334,
6159,
18,
389,
17956,
9384,
16,
4463,
813,
1865,
326,
2430,
903,
506,
25966,
18,
389,
4963,
9384,
16,
2078,
4681,
2430,
4591,
384,
9477,
364,
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,
11162,
38,
321,
12,
203,
3639,
2254,
5034,
389,
8949,
16,
203,
3639,
2254,
5034,
389,
17956,
9384,
16,
203,
3639,
2254,
5034,
389,
4963,
9384,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
5034,
18305,
6275,
13,
288,
203,
3639,
18305,
6275,
273,
14015,
67,
8949,
380,
389,
17956,
9384,
13,
342,
389,
4963,
9384,
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
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./ERC9981155Extension.sol";
import "./ERC998ERC20Extension.sol";
import "../utils/ContractKeys.sol";
import "../interfaces/IBundleBuilder.sol";
import "../interfaces/INftfiBundler.sol";
import "../interfaces/INftfiHub.sol";
import "../interfaces/IPermittedNFTs.sol";
import "../interfaces/IPermittedERC20s.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
/**
* @title NftfiBundler
* @author NFTfi
* @dev ERC998 Top-Down Composable Non-Fungible Token that supports permitted ERC721, ERC1155 and ERC20 children.
*/
contract NftfiBundler is IBundleBuilder, ERC9981155Extension, ERC998ERC20Extension {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
INftfiHub public immutable hub;
event NewBundle(uint256 bundleId, address indexed sender, address indexed receiver);
/**
* @dev Stores the NftfiHub, name and symbol
*
* @param _nftfiHub Address of the NftfiHub contract
* @param _name name of the token contract
* @param _symbol symbol of the token contract
*/
constructor(
address _nftfiHub,
string memory _name,
string memory _symbol
) ERC721(_name, _symbol) {
hub = INftfiHub(_nftfiHub);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId)
public
view
virtual
override(ERC9981155Extension, ERC998ERC20Extension)
returns (bool)
{
return
_interfaceId == type(IERC721Receiver).interfaceId ||
_interfaceId == type(INftfiBundler).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Tells if an asset is permitted or not
* @param _asset address of the asset
* @return true if permitted, false otherwise
*/
function permittedAsset(address _asset) public view returns (bool) {
IPermittedNFTs permittedNFTs = IPermittedNFTs(hub.getContract(ContractKeys.PERMITTED_NFTS));
return permittedNFTs.getNFTPermit(_asset) > 0;
}
/**
* @notice Tells if the erc20 is permitted or not
* @param _erc20Contract address of the erc20
* @return true if permitted, false otherwise
*/
function permittedErc20Asset(address _erc20Contract) public view returns (bool) {
IPermittedERC20s permittedERC20s = IPermittedERC20s(hub.getContract(ContractKeys.PERMITTED_BUNDLE_ERC20S));
return permittedERC20s.getERC20Permit(_erc20Contract);
}
/**
* @dev used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external override returns (uint256) {
uint256 bundleId = _safeMint(_receiver);
require(
_bundleElements.erc721s.length > 0 ||
_bundleElements.erc20s.length > 0 ||
_bundleElements.erc1155s.length > 0,
"bundle is empty"
);
for (uint256 i = 0; i < _bundleElements.erc721s.length; i++) {
if (_bundleElements.erc721s[i].safeTransferable) {
IERC721(_bundleElements.erc721s[i].tokenContract).safeTransferFrom(
_sender,
address(this),
_bundleElements.erc721s[i].id,
abi.encodePacked(bundleId)
);
} else {
_getChild(_sender, bundleId, _bundleElements.erc721s[i].tokenContract, _bundleElements.erc721s[i].id);
}
}
for (uint256 i = 0; i < _bundleElements.erc20s.length; i++) {
_getERC20(_sender, bundleId, _bundleElements.erc20s[i].tokenContract, _bundleElements.erc20s[i].amount);
}
for (uint256 i = 0; i < _bundleElements.erc1155s.length; i++) {
IERC1155(_bundleElements.erc1155s[i].tokenContract).safeBatchTransferFrom(
_sender,
address(this),
_bundleElements.erc1155s[i].ids,
_bundleElements.erc1155s[i].amounts,
abi.encodePacked(bundleId)
);
}
emit NewBundle(bundleId, _sender, _receiver);
return bundleId;
}
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external override nonReentrant {
require(ownerOf(_tokenId) == msg.sender, "caller is not owner");
_validateReceiver(_receiver);
// In each iteration all contracts children are removed, so eventually all contracts are removed
while (childContracts[_tokenId].length() > 0) {
address childContract = childContracts[_tokenId].at(0);
// In each iteration a child is removed, so eventually all contracts children are removed
while (childTokens[_tokenId][childContract].length() > 0) {
uint256 childId = childTokens[_tokenId][childContract].at(0);
uint256 balance = balances[_tokenId][childContract][childId];
if (balance > 0) {
_remove1155Child(_tokenId, childContract, childId, balance);
IERC1155(childContract).safeTransferFrom(address(this), _receiver, childId, balance, "");
emit Transfer1155Child(_tokenId, _receiver, childContract, childId, balance);
} else {
_removeChild(_tokenId, childContract, childId);
try IERC721(childContract).safeTransferFrom(address(this), _receiver, childId) {
// solhint-disable-previous-line no-empty-blocks
} catch {
_oldNFTsTransfer(_receiver, childContract, childId);
}
emit TransferChild(_tokenId, _receiver, childContract, childId);
}
}
}
// In each iteration all contracts children are removed, so eventually all contracts are removed
while (erc20ChildContracts[_tokenId].length() > 0) {
address erc20Contract = erc20ChildContracts[_tokenId].at(0);
uint256 balance = erc20Balances[_tokenId][erc20Contract];
_removeERC20(_tokenId, erc20Contract, balance);
IERC20(erc20Contract).safeTransfer(_receiver, balance);
emit TransferERC20(_tokenId, _receiver, erc20Contract, balance);
}
}
/**
* @dev Update the state to receive a ERC721 child
* Overrides the implementation to check if the asset is permitted
* @param _from The owner of the child token
* @param _tokenId The token receiving the child
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
*/
function _receiveChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual override {
require(permittedAsset(_childContract), "erc721 not permitted");
super._receiveChild(_from, _tokenId, _childContract, _childTokenId);
}
/**
* @dev Updates the state to receive a ERC1155 child
* Overrides the implementation to check if the asset is permitted
* @param _tokenId The token receiving the child
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
*/
function _receive1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual override {
require(permittedAsset(_childContract), "erc1155 not permitted");
super._receive1155Child(_tokenId, _childContract, _childTokenId, _amount);
}
/**
* @notice Store data for the received ERC20
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _receiveErc20Child(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual override {
require(permittedErc20Asset(_erc20Contract), "erc20 not permitted");
super._receiveErc20Child(_from, _tokenId, _erc20Contract, _value);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "./ERC998TopDown.sol";
import "../interfaces/IERC998ERC1155TopDown.sol";
/**
* @title ERC9981155Extension
* @author NFTfi
* @dev ERC998TopDown extension to support ERC1155 children
*/
abstract contract ERC9981155Extension is ERC998TopDown, IERC998ERC1155TopDown, IERC1155Receiver {
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
// tokenId => (child address => (child tokenId => balance))
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal balances;
/**
* @dev Gives child balance for a specific child contract and child id
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the child token
*/
function childBalance(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) external view override returns (uint256) {
return balances[_tokenId][_childContract][_childTokenId];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId)
public
view
virtual
override(ERC998TopDown, IERC165)
returns (bool)
{
return
_interfaceId == type(IERC998ERC1155TopDown).interfaceId ||
_interfaceId == type(IERC1155Receiver).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Transfer a ERC1155 child token from top-down composable to address or other top-down composable
* @param _tokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _amount The amount of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeTransferChild(
uint256 _tokenId,
address _to,
address _childContract,
uint256 _childTokenId,
uint256 _amount,
bytes memory _data
) external override nonReentrant {
_validateReceiver(_to);
_validate1155ChildTransfer(_tokenId);
_remove1155Child(_tokenId, _childContract, _childTokenId, _amount);
if (_to == address(this)) {
_validateAndReceive1155Child(msg.sender, _childContract, _childTokenId, _amount, _data);
} else {
IERC1155(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _amount, _data);
emit Transfer1155Child(_tokenId, _to, _childContract, _childTokenId, _amount);
}
}
/**
* @notice Transfer batch of ERC1155 child token from top-down composable to address or other top-down composable
* @param _tokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenIds The list of tokenId of the token that is being transferred
* @param _amounts The list of amount of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeBatchTransferChild(
uint256 _tokenId,
address _to,
address _childContract,
uint256[] memory _childTokenIds,
uint256[] memory _amounts,
bytes memory _data
) external override nonReentrant {
require(_childTokenIds.length == _amounts.length, "ids and amounts length mismatch");
_validateReceiver(_to);
_validate1155ChildTransfer(_tokenId);
for (uint256 i = 0; i < _childTokenIds.length; ++i) {
uint256 childTokenId = _childTokenIds[i];
uint256 amount = _amounts[i];
_remove1155Child(_tokenId, _childContract, childTokenId, amount);
if (_to == address(this)) {
_validateAndReceive1155Child(msg.sender, _childContract, childTokenId, amount, _data);
}
}
if (_to != address(this)) {
IERC1155(_childContract).safeBatchTransferFrom(address(this), _to, _childTokenIds, _amounts, _data);
emit Transfer1155BatchChild(_tokenId, _to, _childContract, _childTokenIds, _amounts);
}
}
/**
* @notice A token receives a child token
*/
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) external virtual override returns (bytes4) {
revert("external calls restricted");
}
/**
* @notice A token receives a batch of child tokens
* param The address that caused the transfer
* @param _from The owner of the child token
* @param _ids The list of token id that is being transferred to the parent
* @param _values The list of amounts of the tokens that is being transferred
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return the selector of this method
*/
function onERC1155BatchReceived(
address,
address _from,
uint256[] memory _ids,
uint256[] memory _values,
bytes memory _data
) external virtual override nonReentrant returns (bytes4) {
require(_data.length == 32, "data must contain tokenId to transfer the child token to");
uint256 _receiverTokenId = _parseTokenId(_data);
for (uint256 i = 0; i < _ids.length; i++) {
_receive1155Child(_receiverTokenId, msg.sender, _ids[i], _values[i]);
emit Received1155Child(_from, _receiverTokenId, msg.sender, _ids[i], _values[i]);
}
return this.onERC1155BatchReceived.selector;
}
/**
* @dev Validates the data of the child token and receives it
* @param _from The owner of the child token
* @param _childContract The ERC1155 contract of the child token
* @param _id The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
*/
function _validateAndReceive1155Child(
address _from,
address _childContract,
uint256 _id,
uint256 _amount,
bytes memory _data
) internal virtual {
require(_data.length == 32, "data must contain tokenId to transfer the child token to");
uint256 _receiverTokenId = _parseTokenId(_data);
_receive1155Child(_receiverTokenId, _childContract, _id, _amount);
emit Received1155Child(_from, _receiverTokenId, _childContract, _id, _amount);
}
/**
* @dev Updates the state to receive a child
* @param _tokenId The token receiving the child
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The token id that is being transferred to the parent
* @param _amount The amount of the token that is being transferred
*/
function _receive1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length();
if (childTokensLength == 0) {
childContracts[_tokenId].add(_childContract);
}
childTokens[_tokenId][_childContract].add(_childTokenId);
balances[_tokenId][_childContract][_childTokenId] += _amount;
}
/**
* @notice Validates the transfer of a 1155 child
* @param _fromTokenId The owning token to transfer from
*/
function _validate1155ChildTransfer(uint256 _fromTokenId) internal virtual {
_validateTransferSender(_fromTokenId);
}
/**
* @notice Updates the state to remove a ERC1155 child
* @param _tokenId The owning token to transfer from
* @param _childContract The ERC1155 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _amount The amount of the token that is being transferred
*/
function _remove1155Child(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId,
uint256 _amount
) internal virtual {
require(
_amount != 0 && balances[_tokenId][_childContract][_childTokenId] >= _amount,
"insufficient child balance for transfer"
);
balances[_tokenId][_childContract][_childTokenId] -= _amount;
if (balances[_tokenId][_childContract][_childTokenId] == 0) {
// remove child token
childTokens[_tokenId][_childContract].remove(_childTokenId);
// remove contract
if (childTokens[_tokenId][_childContract].length() == 0) {
childContracts[_tokenId].remove(_childContract);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "./ERC998TopDown.sol";
import "../interfaces/IERC998ERC20TopDown.sol";
import "../interfaces/IERC998ERC20TopDownEnumerable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol";
/**
* @title ERC998ERC20Extension
* @author NFTfi
* @dev ERC998TopDown extension to support ERC20 children
*/
abstract contract ERC998ERC20Extension is ERC998TopDown, IERC998ERC20TopDown, IERC998ERC20TopDownEnumerable {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
// tokenId => ERC20 child contract
mapping(uint256 => EnumerableSet.AddressSet) internal erc20ChildContracts;
// tokenId => (token contract => balance)
mapping(uint256 => mapping(address => uint256)) internal erc20Balances;
/**
* @dev Look up the balance of ERC20 tokens for a specific token and ERC20 contract
* @param _tokenId The token that owns the ERC20 tokens
* @param _erc20Contract The ERC20 contract
* @return The number of ERC20 tokens owned by a token
*/
function balanceOfERC20(uint256 _tokenId, address _erc20Contract) external view virtual override returns (uint256) {
return erc20Balances[_tokenId][_erc20Contract];
}
/**
* @notice Get ERC20 contract by tokenId and index
* @param _tokenId The parent token of ERC20 tokens
* @param _index The index position of the child contract
* @return childContract The contract found at the tokenId and index
*/
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view virtual override returns (address) {
return erc20ChildContracts[_tokenId].at(_index);
}
/**
* @notice Get the total number of ERC20 tokens owned by tokenId
* @param _tokenId The parent token of ERC20 tokens
* @return uint256 The total number of ERC20 tokens
*/
function totalERC20Contracts(uint256 _tokenId) external view virtual override returns (uint256) {
return erc20ChildContracts[_tokenId].length();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC998TopDown) returns (bool) {
return
_interfaceId == type(IERC998ERC20TopDown).interfaceId ||
_interfaceId == type(IERC998ERC20TopDownEnumerable).interfaceId ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Transfer ERC20 tokens to address
* @param _tokenId The token to transfer from
* @param _to The address to send the ERC20 tokens to
* @param _erc20Contract The ERC20 contract
* @param _value The number of ERC20 tokens to transfer
*/
function transferERC20(
uint256 _tokenId,
address _to,
address _erc20Contract,
uint256 _value
) external virtual override {
_validateERC20Value(_value);
_validateReceiver(_to);
_validateERC20Transfer(_tokenId);
_removeERC20(_tokenId, _erc20Contract, _value);
IERC20(_erc20Contract).safeTransfer(_to, _value);
emit TransferERC20(_tokenId, _to, _erc20Contract, _value);
}
/**
* @notice Get ERC20 tokens from ERC20 contract.
* @dev This contract has to be approved first by _erc20Contract
*/
function getERC20(
address,
uint256,
address,
uint256
) external pure override {
revert("external calls restricted");
}
/**
* @notice NOT SUPPORTED
* Intended to transfer ERC223 tokens. ERC223 tokens can be transferred as regular ERC20
*/
function transferERC223(
uint256,
address,
address,
uint256,
bytes calldata
) external virtual override {
revert("TRANSFER_ERC223_NOT_SUPPORTED");
}
/**
* @notice NOT SUPPORTED
* Intended to receive ERC223 tokens. ERC223 tokens can be deposited as regular ERC20
*/
function tokenFallback(
address,
uint256,
bytes calldata
) external virtual override {
revert("TOKEN_FALLBACK_ERC223_NOT_SUPPORTED");
}
/**
* @notice Get ERC20 tokens from ERC20 contract.
* @dev This contract has to be approved first by _erc20Contract
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _getERC20(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal {
_validateERC20Value(_value);
_receiveErc20Child(_from, _tokenId, _erc20Contract, _value);
IERC20(_erc20Contract).safeTransferFrom(_from, address(this), _value);
}
/**
* @notice Validates the value of a ERC20 transfer
* @param _value The number of ERC20 tokens to transfer
*/
function _validateERC20Value(uint256 _value) internal virtual {
require(_value > 0, "zero amount");
}
/**
* @notice Validates the transfer of a ERC20
* @param _fromTokenId The owning token to transfer from
*/
function _validateERC20Transfer(uint256 _fromTokenId) internal virtual {
_validateTransferSender(_fromTokenId);
}
/**
* @notice Store data for the received ERC20
* @param _from The current owner address of the ERC20 tokens that are being transferred.
* @param _tokenId The token to transfer the ERC20 tokens to.
* @param _erc20Contract The ERC20 token contract
* @param _value The number of ERC20 tokens to transfer
*/
function _receiveErc20Child(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
if (erc20Balance == 0) {
erc20ChildContracts[_tokenId].add(_erc20Contract);
}
erc20Balances[_tokenId][_erc20Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc20Contract, _value);
}
/**
* @notice Updates the state to remove ERC20 tokens
* @param _tokenId The token to transfer from
* @param _erc20Contract The ERC20 contract
* @param _value The number of ERC20 tokens to transfer
*/
function _removeERC20(
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
require(erc20Balance >= _value, "not enough token available to transfer");
uint256 newERC20Balance = erc20Balance - _value;
erc20Balances[_tokenId][_erc20Contract] = newERC20Balance;
if (newERC20Balance == 0) {
erc20ChildContracts[_tokenId].remove(_erc20Contract);
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title ContractKeys
* @author NFTfi
* @dev Common library for contract keys
*/
library ContractKeys {
bytes32 public constant PERMITTED_ERC20S = bytes32("PERMITTED_ERC20S");
bytes32 public constant PERMITTED_NFTS = bytes32("PERMITTED_NFTS");
bytes32 public constant PERMITTED_PARTNERS = bytes32("PERMITTED_PARTNERS");
bytes32 public constant NFT_TYPE_REGISTRY = bytes32("NFT_TYPE_REGISTRY");
bytes32 public constant LOAN_REGISTRY = bytes32("LOAN_REGISTRY");
bytes32 public constant PERMITTED_SNFT_RECEIVER = bytes32("PERMITTED_SNFT_RECEIVER");
bytes32 public constant PERMITTED_BUNDLE_ERC20S = bytes32("PERMITTED_BUNDLE_ERC20S");
bytes32 public constant PERMITTED_AIRDROPS = bytes32("PERMITTED_AIRDROPS");
bytes32 public constant AIRDROP_RECEIVER = bytes32("AIRDROP_RECEIVER");
bytes32 public constant AIRDROP_FACTORY = bytes32("AIRDROP_FACTORY");
bytes32 public constant AIRDROP_FLASH_LOAN = bytes32("AIRDROP_FLASH_LOAN");
bytes32 public constant NFTFI_BUNDLER = bytes32("NFTFI_BUNDLER");
string public constant AIRDROP_WRAPPER_STRING = "AirdropWrapper";
/**
* @notice Returns the bytes32 representation of a string
* @param _key the string key
* @return id bytes32 representation
*/
function getIdFromStringKey(string memory _key) external pure returns (bytes32 id) {
require(bytes(_key).length <= 32, "invalid key");
// solhint-disable-next-line no-inline-assembly
assembly {
id := mload(add(_key, 32))
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IBundleBuilder {
/**
* @notice data of a erc721 bundle element
*
* @param tokenContract - address of the token contract
* @param id - id of the token
* @param safeTransferable - wether the implementing token contract has a safeTransfer function or not
*/
struct BundleElementERC721 {
address tokenContract;
uint256 id;
bool safeTransferable;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param amount - amount of the token
*/
struct BundleElementERC20 {
address tokenContract;
uint256 amount;
}
/**
* @notice data of a erc20 bundle element
*
* @param tokenContract - address of the token contract
* @param ids - list of ids of the tokens
* @param amounts - list amounts of the tokens
*/
struct BundleElementERC1155 {
address tokenContract;
uint256[] ids;
uint256[] amounts;
}
/**
* @notice the lists of erc721-20-1155 tokens that are to be bundled
*
* @param erc721s list of erc721 tokens
* @param erc20s list of erc20 tokens
* @param erc1155s list of erc1155 tokens
*/
struct BundleElements {
BundleElementERC721[] erc721s;
BundleElementERC20[] erc20s;
BundleElementERC1155[] erc1155s;
}
/**
* @notice used by the loan contract to build a bundle from the BundleElements struct at the beginning of a loan,
* returns the id of the created bundle
*
* @param _bundleElements - the lists of erc721-20-1155 tokens that are to be bundled
* @param _sender sender of the tokens in the bundle - the borrower
* @param _receiver receiver of the created bundle, normally the loan contract
*/
function buildBundle(
BundleElements memory _bundleElements,
address _sender,
address _receiver
) external returns (uint256);
/**
* @notice Remove all the children from the bundle
* @dev This method may run out of gas if the list of children is too big. In that case, children can be removed
* individually.
* @param _tokenId the id of the bundle
* @param _receiver address of the receiver of the children
*/
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./IERC998ERC721TopDown.sol";
interface INftfiBundler is IERC721 {
function safeMint(address _to) external returns (uint256);
function decomposeBundle(uint256 _tokenId, address _receiver) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
/**
* @title INftfiHub
* @author NFTfi
* @dev NftfiHub interface
*/
interface INftfiHub {
function setContract(string calldata _contractKey, address _contractAddress) external;
function getContract(bytes32 _contractKey) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedNFTs {
function setNFTPermit(address _nftContract, string memory _nftType) external;
function getNFTPermit(address _nftContract) external view returns (bytes32);
function getNFTWrapper(address _nftContract) external view returns (address);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IPermittedERC20s {
function getERC20Permit(address _erc20) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: 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.
*
* NOTE: 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: BUSL-1.1
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IERC998ERC721TopDown.sol";
import "../interfaces/IERC998ERC721TopDownEnumerable.sol";
/**
* @title ERC998TopDown
* @author NFTfi
* @dev ERC998ERC721 Top-Down Composable Non-Fungible Token.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-998.md
* This implementation does not support children to be nested bundles, erc20 nor bottom-up
*/
abstract contract ERC998TopDown is
ERC721Enumerable,
IERC998ERC721TopDown,
IERC998ERC721TopDownEnumerable,
ReentrancyGuard
{
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableSet for EnumerableSet.AddressSet;
// return this.rootOwnerOf.selector ^ this.rootOwnerOfChild.selector ^
// this.tokenOwnerOf.selector ^ this.ownerOfChild.selector;
bytes32 public constant ERC998_MAGIC_VALUE = 0xcd740db500000000000000000000000000000000000000000000000000000000;
bytes32 internal constant ERC998_MAGIC_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000;
uint256 public tokenCount = 0;
// tokenId => child contract
mapping(uint256 => EnumerableSet.AddressSet) internal childContracts;
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => EnumerableSet.UintSet)) internal childTokens;
// child address => childId => tokenId
// this is used for ERC721 type tokens
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
/**
* @notice Tells whether the ERC721 type child exists or not
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return True if the child exists, false otherwise
*/
function childExists(address _childContract, uint256 _childTokenId) external view virtual returns (bool) {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return tokenId != 0;
}
/**
* @notice Get the total number of child contracts with tokens that are owned by _tokenId
* @param _tokenId The parent token of child tokens in child contracts
* @return uint256 The total number of child contracts with tokens owned by _tokenId
*/
function totalChildContracts(uint256 _tokenId) external view virtual override returns (uint256) {
return childContracts[_tokenId].length();
}
/**
* @notice Get child contract by tokenId and index
* @param _tokenId The parent token of child tokens in child contract
* @param _index The index position of the child contract
* @return childContract The contract found at the _tokenId and index
*/
function childContractByIndex(uint256 _tokenId, uint256 _index)
external
view
virtual
override
returns (address childContract)
{
return childContracts[_tokenId].at(_index);
}
/**
* @notice Get the total number of child tokens owned by tokenId that exist in a child contract
* @param _tokenId The parent token of child tokens
* @param _childContract The child contract containing the child tokens
* @return uint256 The total number of child tokens found in child contract that are owned by _tokenId
*/
function totalChildTokens(uint256 _tokenId, address _childContract) external view override returns (uint256) {
return childTokens[_tokenId][_childContract].length();
}
/**
* @notice Get child token owned by _tokenId, in child contract, at index position
* @param _tokenId The parent token of the child token
* @param _childContract The child contract of the child token
* @param _index The index position of the child token
* @return childTokenId The child tokenId for the parent token, child token and index
*/
function childTokenByIndex(
uint256 _tokenId,
address _childContract,
uint256 _index
) external view virtual override returns (uint256 childTokenId) {
return childTokens[_tokenId][_childContract].at(_index);
}
/**
* @notice Get the parent tokenId and its owner of a ERC721 child token
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return parentTokenOwner The parent address of the parent token and ERC998 magic value
* @return parentTokenId The parent tokenId of _childTokenId
*/
function ownerOfChild(address _childContract, uint256 _childTokenId)
external
view
virtual
override
returns (bytes32 parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId != 0, "owner of child not found");
address parentTokenOwnerAddress = ownerOf(parentTokenId);
// solhint-disable-next-line no-inline-assembly
assembly {
parentTokenOwner := or(ERC998_MAGIC_VALUE, parentTokenOwnerAddress)
}
}
/**
* @notice Get the root owner of tokenId
* @param _tokenId The token to query for a root owner address
* @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value.
*/
function rootOwnerOf(uint256 _tokenId) public view virtual override returns (bytes32 rootOwner) {
return rootOwnerOfChild(address(0), _tokenId);
}
/**
* @notice Get the root owner of a child token
* @dev Returns the owner at the top of the tree of composables
* Use Cases handled:
* - Case 1: Token owner is this contract and token.
* - Case 2: Token owner is other external top-down composable
* - Case 3: Token owner is other contract
* - Case 4: Token owner is user
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return rootOwner The root owner at the top of tree of tokens and ERC998 magic value
*/
function rootOwnerOfChild(address _childContract, uint256 _childTokenId)
public
view
virtual
override
returns (bytes32 rootOwner)
{
address rootOwnerAddress;
if (_childContract != address(0)) {
(rootOwnerAddress, _childTokenId) = _ownerOfChild(_childContract, _childTokenId);
} else {
rootOwnerAddress = ownerOf(_childTokenId);
}
if (rootOwnerAddress.isContract()) {
try IERC998ERC721TopDown(rootOwnerAddress).rootOwnerOfChild(address(this), _childTokenId) returns (
bytes32 returnedRootOwner
) {
// Case 2: Token owner is other external top-down composable
if (returnedRootOwner & ERC998_MAGIC_MASK == ERC998_MAGIC_VALUE) {
return returnedRootOwner;
}
} catch {
// solhint-disable-previous-line no-empty-blocks
}
}
// Case 3: Token owner is other contract
// Or
// Case 4: Token owner is user
// solhint-disable-next-line no-inline-assembly
assembly {
rootOwner := or(ERC998_MAGIC_VALUE, rootOwnerAddress)
}
return rootOwner;
}
/**
* @dev See {IERC165-supportsInterface}.
* The interface id 0x1efdf36a is added. The spec claims it to be the interface id of IERC998ERC721TopDown.
* But it is not.
* It is added anyway in case some contract checks it being compliant with the spec.
*/
function supportsInterface(bytes4 _interfaceId) public view virtual override(ERC721Enumerable) returns (bool) {
return
_interfaceId == type(IERC998ERC721TopDown).interfaceId ||
_interfaceId == type(IERC998ERC721TopDownEnumerable).interfaceId ||
_interfaceId == 0x1efdf36a ||
super.supportsInterface(_interfaceId);
}
/**
* @notice Mints a new bundle
* @param _to The address that owns the new bundle
* @return The id of the new bundle
*/
function _safeMint(address _to) internal returns (uint256) {
uint256 id = ++tokenCount;
_safeMint(_to, id);
return id;
}
/**
* @notice Transfer child token from top-down composable to address
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
/**
* @notice Transfer child token from top-down composable to address or other top-down composable
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
* @param _data Additional data with no specified format
*/
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
if (_to == address(this)) {
_validateAndReceiveChild(msg.sender, _childContract, _childTokenId, _data);
} else {
IERC721(_childContract).safeTransferFrom(address(this), _to, _childTokenId, _data);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
}
/**
* @dev Transfer child token from top-down composable to address
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external virtual override nonReentrant {
_transferChild(_fromTokenId, _to, _childContract, _childTokenId);
_oldNFTsTransfer(_to, _childContract, _childTokenId);
emit TransferChild(_fromTokenId, _to, _childContract, _childTokenId);
}
/**
* @notice NOT SUPPORTED
* Intended to transfer bottom-up composable child token from top-down composable to other ERC721 token.
*/
function transferChildToParent(
uint256,
address,
uint256,
address,
uint256,
bytes memory
) external pure override {
revert("BOTTOM_UP_CHILD_NOT_SUPPORTED");
}
/**
* @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not
* have a safeTransferFrom method like cryptokitties
*/
function getChild(
address,
uint256,
address,
uint256
) external pure override {
revert("external calls restricted");
}
/**
* @notice Transfer a child token from an ERC721 contract to a composable. Used for old tokens that does not
* have a safeTransferFrom method like cryptokitties
* @dev This contract has to be approved first in _childContract
* @param _from The address that owns the child token.
* @param _tokenId The token that becomes the parent owner
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the child token
*/
function _getChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual nonReentrant {
_receiveChild(_from, _tokenId, _childContract, _childTokenId);
IERC721(_childContract).transferFrom(_from, address(this), _childTokenId);
}
/**
* @notice A token receives a child token
* param The address that caused the transfer
* @param _from The owner of the child token
* @param _childTokenId The token that is being transferred to the parent
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return the selector of this method
*/
function onERC721Received(
address,
address _from,
uint256 _childTokenId,
bytes calldata _data
) external virtual override nonReentrant returns (bytes4) {
_validateAndReceiveChild(_from, msg.sender, _childTokenId, _data);
return this.onERC721Received.selector;
}
/**
* @dev ERC721 implementation hook that is called before any token transfer. Prevents nested bundles
* @param _from address of the current owner of the token
* @param _to destination address
* @param _tokenId id of the token to transfer
*/
function _beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) internal virtual override {
require(_to != address(this), "nested bundles not allowed");
super._beforeTokenTransfer(_from, _to, _tokenId);
}
/**
* @dev Validates the child transfer parameters and remove the child from the bundle
* @param _fromTokenId The owning token to transfer from
* @param _to The address that receives the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) internal virtual {
_validateReceiver(_to);
_validateChildTransfer(_fromTokenId, _childContract, _childTokenId);
_removeChild(_fromTokenId, _childContract, _childTokenId);
}
/**
* @dev Validates the child transfer parameters
* @param _fromTokenId The owning token to transfer from
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _validateChildTransfer(
uint256 _fromTokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
require(tokenId != 0, "_transferChild _childContract _childTokenId not found");
require(tokenId == _fromTokenId, "ComposableTopDown: _transferChild wrong tokenId found");
_validateTransferSender(tokenId);
}
/**
* @dev Validates the receiver of a child transfer
* @param _to The address that receives the child token
*/
function _validateReceiver(address _to) internal virtual {
require(_to != address(0), "child transfer to zero address");
}
/**
* @dev Updates the state to remove a child
* @param _tokenId The owning token to transfer from
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The tokenId of the token that is being transferred
*/
function _removeChild(
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
// remove child token
childTokens[_tokenId][_childContract].remove(_childTokenId);
delete childTokenOwner[_childContract][_childTokenId];
// remove contract
if (childTokens[_tokenId][_childContract].length() == 0) {
childContracts[_tokenId].remove(_childContract);
}
}
/**
* @dev Validates the data from a child transfer and receives it
* @param _from The owner of the child token
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
*/
function _validateAndReceiveChild(
address _from,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) internal virtual {
require(_data.length > 0, "data must contain tokenId to transfer the child token to");
// convert up to 32 bytes of _data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId = _parseTokenId(_data);
_receiveChild(_from, tokenId, _childContract, _childTokenId);
}
/**
* @dev Update the state to receive a child
* @param _from The owner of the child token
* @param _tokenId The token receiving the child
* @param _childContract The ERC721 contract of the child token
* @param _childTokenId The token that is being transferred to the parent
*/
function _receiveChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) internal virtual {
require(_exists(_tokenId), "bundle tokenId does not exist");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length();
if (childTokensLength == 0) {
childContracts[_tokenId].add(_childContract);
}
childTokens[_tokenId][_childContract].add(_childTokenId);
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
/**
* @dev Returns the owner of a child
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
* @return parentTokenOwner The parent address of the parent token and ERC998 magic value
* @return parentTokenId The parent tokenId of _childTokenId
*/
function _ownerOfChild(address _childContract, uint256 _childTokenId)
internal
view
virtual
returns (address parentTokenOwner, uint256 parentTokenId)
{
parentTokenId = childTokenOwner[_childContract][_childTokenId];
require(parentTokenId != 0, "owner of child not found");
return (ownerOf(parentTokenId), parentTokenId);
}
/**
* @dev Convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
* @param _data Up to the first 32 bytes contains an integer which is the receiving parent tokenId
* @return tokenId the token Id encoded in the data
*/
function _parseTokenId(bytes memory _data) internal pure virtual returns (uint256 tokenId) {
// solhint-disable-next-line no-inline-assembly
assembly {
tokenId := mload(add(_data, 0x20))
}
}
/**
* @dev Transfers the NFT using method compatible with old token contracts
* @param _to address of the receiver of the children
* @param _childContract The contract address of the child token
* @param _childTokenId The tokenId of the child
*/
function _oldNFTsTransfer(
address _to,
address _childContract,
uint256 _childTokenId
) internal {
// This is here to be compatible with cryptokitties and other old contracts that require being owner and
// approved before transferring.
// Does not work with current standard which does not allow approving self, so we must let it fail in that case.
try IERC721(_childContract).approve(address(this), _childTokenId) {
// solhint-disable-previous-line no-empty-blocks
} catch {
// solhint-disable-previous-line no-empty-blocks
}
IERC721(_childContract).transferFrom(address(this), _to, _childTokenId);
}
/**
* @notice Validates that the sender is authorized to perform a child transfer
* @param _fromTokenId The owning token to transfer from
*/
function _validateTransferSender(uint256 _fromTokenId) internal virtual {
address rootOwner = address(uint160(uint256(rootOwnerOf(_fromTokenId))));
require(
rootOwner == msg.sender ||
getApproved(_fromTokenId) == msg.sender ||
isApprovedForAll(rootOwner, msg.sender),
"transferChild msg.sender not eligible"
);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC1155TopDown {
event Received1155Child(
address indexed from,
uint256 indexed toTokenId,
address indexed childContract,
uint256 childTokenId,
uint256 amount
);
event Transfer1155Child(
uint256 indexed fromTokenId,
address indexed to,
address indexed childContract,
uint256 childTokenId,
uint256 amount
);
event Transfer1155BatchChild(
uint256 indexed fromTokenId,
address indexed to,
address indexed childContract,
uint256[] childTokenIds,
uint256[] amounts
);
function safeTransferChild(
uint256 fromTokenId,
address to,
address childContract,
uint256 childTokenId,
uint256 amount,
bytes calldata data
) external;
function safeBatchTransferChild(
uint256 fromTokenId,
address to,
address childContract,
uint256[] calldata childTokenIds,
uint256[] calldata amounts,
bytes calldata data
) external;
function childBalance(
uint256 tokenId,
address childContract,
uint256 childTokenId
) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC721TopDown {
event ReceivedChild(
address indexed _from,
uint256 indexed _tokenId,
address indexed _childContract,
uint256 _childTokenId
);
event TransferChild(
uint256 indexed tokenId,
address indexed _to,
address indexed _childContract,
uint256 _childTokenId
);
function onERC721Received(
address _operator,
address _from,
uint256 _childTokenId,
bytes calldata _data
) external returns (bytes4);
function transferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external;
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId
) external;
function safeTransferChild(
uint256 _fromTokenId,
address _to,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external;
function transferChildToParent(
uint256 _fromTokenId,
address _toContract,
uint256 _toTokenId,
address _childContract,
uint256 _childTokenId,
bytes memory _data
) external;
// getChild function enables older contracts like cryptokitties to be transferred into a composable
// The _childContract must approve this contract. Then getChild can be called.
function getChild(
address _from,
uint256 _tokenId,
address _childContract,
uint256 _childTokenId
) external;
function rootOwnerOf(uint256 _tokenId) external view returns (bytes32 rootOwner);
function rootOwnerOfChild(address _childContract, uint256 _childTokenId) external view returns (bytes32 rootOwner);
function ownerOfChild(address _childContract, uint256 _childTokenId)
external
view
returns (bytes32 parentTokenOwner, uint256 parentTokenId);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC721TopDownEnumerable {
function totalChildContracts(uint256 _tokenId) external view returns (uint256);
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract);
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns (uint256);
function childTokenByIndex(
uint256 _tokenId,
address _childContract,
uint256 _index
) external view returns (uint256 childTokenId);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC20TopDown {
event ReceivedERC20(
address indexed _from,
uint256 indexed _tokenId,
address indexed _erc20Contract,
uint256 _value
);
event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc20Contract, uint256 _value);
function balanceOfERC20(uint256 _tokenId, address __erc20Contract) external view returns (uint256);
function tokenFallback(
address _from,
uint256 _value,
bytes calldata _data
) external;
function transferERC20(
uint256 _tokenId,
address _to,
address _erc20Contract,
uint256 _value
) external;
function transferERC223(
uint256 _tokenId,
address _to,
address _erc223Contract,
uint256 _value,
bytes calldata _data
) external;
function getERC20(
address _from,
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
interface IERC998ERC20TopDownEnumerable {
function totalERC20Contracts(uint256 _tokenId) external view returns (uint256);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
} | * @notice Updates the state to remove ERC20 tokens @param _tokenId The token to transfer from @param _erc20Contract The ERC20 contract @param _value The number of ERC20 tokens to transfer/ | function _removeERC20(
uint256 _tokenId,
address _erc20Contract,
uint256 _value
) internal virtual {
uint256 erc20Balance = erc20Balances[_tokenId][_erc20Contract];
require(erc20Balance >= _value, "not enough token available to transfer");
uint256 newERC20Balance = erc20Balance - _value;
erc20Balances[_tokenId][_erc20Contract] = newERC20Balance;
if (newERC20Balance == 0) {
erc20ChildContracts[_tokenId].remove(_erc20Contract);
}
}
| 1,483,186 | [
1,
5121,
326,
919,
358,
1206,
4232,
39,
3462,
2430,
225,
389,
2316,
548,
1021,
1147,
358,
7412,
628,
225,
389,
12610,
3462,
8924,
1021,
4232,
39,
3462,
6835,
225,
389,
1132,
1021,
1300,
434,
4232,
39,
3462,
2430,
358,
7412,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
4479,
654,
39,
3462,
12,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
1758,
389,
12610,
3462,
8924,
16,
203,
3639,
2254,
5034,
389,
1132,
203,
565,
262,
2713,
5024,
288,
203,
3639,
2254,
5034,
6445,
71,
3462,
13937,
273,
6445,
71,
3462,
38,
26488,
63,
67,
2316,
548,
6362,
67,
12610,
3462,
8924,
15533,
203,
3639,
2583,
12,
12610,
3462,
13937,
1545,
389,
1132,
16,
315,
902,
7304,
1147,
2319,
358,
7412,
8863,
203,
3639,
2254,
5034,
394,
654,
39,
3462,
13937,
273,
6445,
71,
3462,
13937,
300,
389,
1132,
31,
203,
3639,
6445,
71,
3462,
38,
26488,
63,
67,
2316,
548,
6362,
67,
12610,
3462,
8924,
65,
273,
394,
654,
39,
3462,
13937,
31,
203,
3639,
309,
261,
2704,
654,
39,
3462,
13937,
422,
374,
13,
288,
203,
5411,
6445,
71,
3462,
1763,
20723,
63,
67,
2316,
548,
8009,
4479,
24899,
12610,
3462,
8924,
1769,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/44787/0x6376bcc4168683778A727C860f465A8c76782888/sources/project_/contracts/ERC20Project.sol | @dev Ownable methods overridden | function transferOwnership(address newOwner) public override onlyOwner {
require(newOwner != address(0), "Ownable: new owner cannot be the zero address");
_transferOwnership(newOwner);
_setupRole(DEFAULT_ADMIN_ROLE, newOwner);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
| 13,268,444 | [
1,
5460,
429,
2590,
11000,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
3849,
1338,
5541,
288,
203,
3639,
2583,
12,
2704,
5541,
480,
1758,
12,
20,
3631,
315,
5460,
429,
30,
394,
3410,
2780,
506,
326,
3634,
1758,
8863,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
394,
5541,
1769,
203,
3639,
1654,
8386,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
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
] |
./full_match/1/0x13068A5cbC89205B0b2bE50eeB282CB84C9Bc25a/sources/contracts/DefaultOperatorFiltererUpgradeable.sol | * @title DefaultOperatorFiltererUpgradeable @notice Inherits from OperatorFiltererUpgradeable and automatically subscribes to the default OpenSea subscription when the init function is called./ | abstract contract DefaultOperatorFiltererUpgradeable is OperatorFiltererUpgradeable {
pragma solidity ^0.8.13;
import {OperatorFiltererUpgradeable} from "./OperatorFiltererUpgradeable.sol";
import {CANONICAL_CORI_SUBSCRIPTION} from "./Constants.sol";
function __DefaultOperatorFilterer_init() internal onlyInitializing {
OperatorFiltererUpgradeable.__OperatorFilterer_init(CANONICAL_CORI_SUBSCRIPTION, true);
}
}
| 17,186,479 | [
1,
1868,
5592,
1586,
264,
10784,
429,
225,
657,
20038,
628,
11097,
1586,
264,
10784,
429,
471,
6635,
10189,
281,
358,
326,
805,
3502,
1761,
69,
4915,
540,
1347,
326,
1208,
445,
353,
2566,
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,
17801,
6835,
2989,
5592,
1586,
264,
10784,
429,
353,
11097,
1586,
264,
10784,
429,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
203,
5666,
288,
5592,
1586,
264,
10784,
429,
97,
628,
25165,
5592,
1586,
264,
10784,
429,
18,
18281,
14432,
203,
5666,
288,
39,
1258,
673,
10109,
67,
9428,
45,
67,
8362,
11133,
97,
628,
25165,
2918,
18,
18281,
14432,
203,
565,
445,
1001,
1868,
5592,
1586,
264,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
3639,
11097,
1586,
264,
10784,
429,
16186,
5592,
1586,
264,
67,
2738,
12,
39,
1258,
673,
10109,
67,
9428,
45,
67,
8362,
11133,
16,
638,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-23
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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 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 IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface 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 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);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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);
_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:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @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 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 {}
}
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;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
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;
}
contract ApeLabs is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
// Seller Map
mapping (address => uint256) private _holderFirstBuyTimestamp;
// Blacklist Map
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
// block number of opened trading
uint256 launchedAt;
/******************/
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("ApeLabs", "LABS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 4;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 6;
uint256 _earlySellDevFee = 4
; uint256 totalSupply = 1 * 1e10 * 1e18;
maxTransactionAmount = totalSupply * 3 / 1000; // 0.3% maxTransactionAmountTxn
maxWallet = totalSupply * 10 / 1000; // 1% maxWallet
swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
// anti bot logic
if (block.number <= (launchedAt + 1) &&
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
// early sell logic
bool isBuy = from == uniswapV2Pair;
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
} else {
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
} else {
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
address(this),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function Airdrop(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount | contract ApeLabs is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool private swapping;
address private marketingWallet;
address private devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public swapEnabled = false;
bool public enableEarlySellTax = true;
mapping (address => uint256) private _holderFirstBuyTimestamp;
mapping (address => bool) private _blacklist;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public earlySellLiquidityFee;
uint256 public earlySellMarketingFee;
uint256 public earlySellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
uint256 launchedAt;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("ApeLabs", "LABS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 2;
uint256 _buyDevFee = 2;
uint256 _sellMarketingFee = 6;
uint256 _sellLiquidityFee = 3;
uint256 _sellDevFee = 4;
uint256 _earlySellLiquidityFee = 3;
uint256 _earlySellMarketingFee = 6;
uint256 _earlySellDevFee = 4
; uint256 totalSupply = 1 * 1e10 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading() external onlyOwner {
tradingActive = true;
swapEnabled = true;
launchedAt = block.number;
}
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
earlySellLiquidityFee = _earlySellLiquidityFee;
earlySellMarketingFee = _earlySellMarketingFee;
earlySellDevFee = _earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 99, "Must keep fees at 25% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function blacklistAccount (address account, bool isBlacklisted) public onlyOwner {
_blacklist[account] = isBlacklisted;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
if (block.number <= (launchedAt + 1) &&
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
bool isBuy = from == uniswapV2Pair;
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
} else {
} else {
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
to != uniswapV2Pair &&
to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)
) {
_blacklist[to] = true;
}
if (!isBuy && enableEarlySellTax) {
if (_holderFirstBuyTimestamp[from] != 0 &&
(_holderFirstBuyTimestamp[from] + (1 hours) >= block.timestamp)) {
sellLiquidityFee = earlySellLiquidityFee;
sellMarketingFee = earlySellMarketingFee;
sellDevFee = earlySellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
sellLiquidityFee = 4;
sellMarketingFee = 4;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
if (_holderFirstBuyTimestamp[to] == 0) {
_holderFirstBuyTimestamp[to] = block.timestamp;
}
if (!enableEarlySellTax) {
sellLiquidityFee = 1;
sellMarketingFee = 7;
sellDevFee = 7;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
address(this),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
(success,) = address(devWallet).call{value: ethForDev}("");
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
function Airdrop(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
function Airdrop(address[] calldata recipients, uint256[] calldata values)
external
onlyOwner
{
_approve(owner(), owner(), totalSupply());
for (uint256 i = 0; i < recipients.length; i++) {
transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals());
}
}
} | 2,072,819 | [
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
4352,
749,
1635,
22467,
1098,
1635,
1203,
1300,
434,
10191,
1284,
7459,
4433,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
432,
347,
48,
5113,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
7010,
565,
1426,
3238,
7720,
1382,
31,
203,
7010,
565,
1758,
3238,
13667,
310,
16936,
31,
203,
565,
1758,
3238,
4461,
16936,
31,
203,
7010,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
7010,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
565,
1426,
1071,
4237,
41,
20279,
55,
1165,
7731,
273,
638,
31,
203,
7010,
7010,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
4505,
3759,
38,
9835,
4921,
31,
203,
7010,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
22491,
31,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
7010,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
30143,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
1071,
30143,
8870,
14667,
31,
203,
7010,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
1071,
357,
80,
2
] |
pragma solidity ^0.4.18;
//
// AddressWars
// (http://beta.addresswars.io/)
// Public Beta
//
//
// .d8888b. .d8888b.
// d88P Y88b d88P Y88b
// 888 888 888 888
// 888 888888 888 888 888.d8888b 888 888888 888
// 888 888`Y8bd8P' 888 88888K 888 888`Y8bd8P'
// 888 888 X88K Y88 88P"Y8888b. 888 888 X88K
// Y88b d88P.d8""8b. Y8bd8P X88 Y88b d88P.d8""8b.
// "Y8888P" 888 888 Y88P 88888P' "Y8888P" 888 888
//
//
// ******************************
// Welcome to AddressWars Beta!
// ******************************
//
// This contract is currently in a state of being tested and bug hunted,
// as this is the beta, there will be no fees for enlisting or wagering.
// This will encourage anyone to come and try out AddressWars for free
// before deciding to play the live version (when released) as well as
// making it so that the contract is tested to the fullest ability before
// the live version is deployed. The website is currently under development
// and will be continually improved as time goes on, once the live version
// is deployed, you can access it's contract and data through the root url
// (https://addresswars.io/) and there will always be a copy of the website
// on a subdomain that you can visit in order to view and interact with this
// contract at any time in the future.
//
// This contract is pushing the limits of the current Ethereum blockchain as
// there are quite a lot of variables that it needs to keep track of as well
// as being able to handle the statistical generation of key numbers. As a
// result, the estimated gas cost to deploy this contract is 7.5M whereas
// the current block gas limit is only 8M so this contract will take up
// almost a whole block! Another problem with complex contracts is the fact
// that there is a 16 local variable limit per function and in a few cases,
// the functions needed access to a lot more than that so a lot of filtering
// functions have been developed to handle the calculation internally then
// simply return the useful parts.
//
//
// **************************
// How to play AddressWars!
// **************************
//
// Enlisting
// In order to start playing AddressWars, you must first have an Ethereum
// wallet address which you can issue transactions from but only non-contract
// addresses (ie addresses where you can issue a transaction directly) can play.
// From here, you can simply call the enlist() function and send the relevant
// fee (in the beta it's 0 ETH, for the live it will be 0.01 ETH). After the
// transaction succeeds, you will have your very own, randomly generated
// address card that you can now put up for wager or use to attempt to claim
// other address cards with!
//
// Wagering
// You can choose to wager any card you own assuming you are not already
// wagering a copy of that card. For your own address, you can provide a
// maximum of 10 other copies to any other addresses (by either transferring
// or wagering), once 10 copies of your own address are circulating, you will
// no longer be able to transfer or wager your own address (although you can
// still use it to claim other addresses). It is important to note that there
// is no way to 'destroy' a copy of a card in circulation and your own address
// card cannot be transferred back to you (and you can't attempt to claim your
// own address card).
// To wager a card, simply call the wagerCardForAmount() function and send
// the relevant fee (in the beta it's 0 ETH, for the live it will be 0.005 ETH)
// as well as the address of the card you wish to wager and the amount you are
// willing to wager it for (in wei). From this point, any other address can
// attempt to claim the address card you listed but the card that will be put up
// for claim will be the one with the lowest claim price (this may not be yours
// at the time but as soon as a successful claim happens and you are the next
// cheapest price, the next time someone attempts to claim that address, you
// will receive the wager and your card may be claimed and taken from you).
//
// Claiming
// Assuming your address has already enlisted, you are free to attempt to
// claim any card that has a current wager on it. You can only store up to
// 8 unique card addresses (your own address + 7 others) in your inventory
// and you cannot claim if you are already at this limit (unless you already own
// that card). You can claim as many copies of a card you own as you like but you
// can only get rid of them by wagering off one at a time. As mentioned above,
// the claim contender will be the owner of the cheapest claim wager. You cannot
// claim a card if you are the current claim contender or if the card address is
// the same as your address (ie you enlisted and got that card).
// To attempt to claim, you need to first assemble an army of 3 address cards
// (these cards don't have to be unique but you do have to own them) and send the
// current cheapest wager price to the attemptToClaimCard() function. This function
// will do all of the calculation work for you and determine if you managed to claim
// the card or not. The first thing that happens is the contract randomly picks
// your claim contenders cards ensuring that at least one of the cards is the card
// address you are attempting to claim and the rest are from their inventory.
// After this point, all of the complex maths happens and the final attack
// and defence numbers will be calculated based on all of the cards types,
// modifiers and the base attack and defence stats.
// From here it's simply a matter of determining how many hits got through
// on both claimer and claim contender, it's calculated as follows;
// opponentsHits = yourCard[attack] - opponentsCard[defence]
// ^ will be 0 if opponentsCard[defence] > yourCard[attack]
// This is totalled up for both the claimer and the claim contender and the
// one with the least amount of hits wins!
//
// Claim Outcomes
// There are 3 situations that can result from a claim attempt;
// 1. The total hits for both the claimer and the claim contender are equal
// - this means that you have drawn with your opponent, the wager will
// then be distributed;
// 98% -> the claimer (you get most of the wager back)
// 2% -> the dev
// 2. The claimer has more hits than the claim contender
// - this means that you have lost against your opponent as they ended
// up taking less hits than you, the wager will then be distributed;
// 98% -> the claim contender (they get most of the wager)
// 2% -> the dev
// 3. The claimer has less hits than the claim contender
// - this means that you have succeeded in claiming the card and hence
// that card address will be transferred from the claim contender
// to the claimer. in this case, both claimer and claim contender
// receive a portion of the wager as follow;
// 50% -> the claimer (you get half of the wager back)
// 48% -> the claim contender (they get about half of the wager)
// 2% -> the dev
//
// Transferring
// You are free to transfer any card you own to another address that has
// already enlisted. Upon transfer, only one copy of the card will be removed
// from your inventory so if you have multiple copies of that card, it will
// not be completely removed from your inventory. If you only had one copy
// though, that address will be removed from your inventory and you will
// be able to claim/receive another address in its place.
// There are some restrictions when transferring a card;
// 1. you cannot be currently wagering the card
// 2. the address you are transferring to must already be enlisted
// 3. the address you are transferring the card to must have less than
// 8 unique cards already (or they must already own the card)
// 4. you cannot transfer a card back to it's original address
// 5. if you are gifting your own address card, the claim limit will apply
// and if 10 copies already exist, you will not be able to gift your card.
//
// Withdrawing
// All ETH transferred to the contract will stay in there until an
// address wishes to withdraw from their account. Balances are tracked
// per address and you can either withdraw an amount (assuming you have
// a balance higher than that amount) or you can just withdraw it all.
// For both of these cases there will be no fees associated with withdrawing
// from the contract and after you choose to withdraw, your balance will
// update accordingly.
//
//
// Have fun and good luck claiming!
//
contract AddressWarsBeta {
//////////////////////////////////////////////////////////////////////
// Constants
// dev
address public dev;
uint256 constant devTax = 2; // 2% of all wagers
// fees
// in the live version the;
// enlistingFee will be 0.01 ether and the
// wageringFee will be 0.005 ether
uint256 constant enlistingFee = 0;
uint256 constant wageringFee = 0;
// limits
// the claim limit represents how many times an address can
// wager/trasnfer their own address. in this case the limit
// is set to 10 which means there can only ever be 10 other
// copies of your address out there. once you have wagered
// all 10 copies, you will no longer be able to wager your
// own address card (although you can still use it in play).
uint256 constant CLAIM_LIMIT = 10;
// this will limit how many unique addresses you can own at
// one time. you can own multiple copies of a unique address
// but you can only own a total of 8 unique addresses (your
// own address + 7 others) at a time. you can choose to wager
// any address but if you wager one, the current claim price is the
// lowest price offered from all owners. upon a successful claim,
// one copy will transfer from your inventory and if you have no
// copies remaining, it will remove that address card and you will
// have another free slot.
uint256 constant MAX_UNIQUE_CARDS_PER_ADDRESS = 8;
//////////////////////////////////////////////////////////////////////
// Statistical Variables
// this is used to calculate all of the statistics and random choices
// within AddressWars
// see the shuffleSeed() and querySeed() methods for more information.
uint256 private _seed;
// the type will determine a cards bonus numbers;
// normal cards do not get any type advantage bonuses
// fire gets 1.25x att and def when versing nature
// water gets 1.25x att and def when versing fire
// nature gets 1.25x att and def when versing water
// *type advantages are applied after all modifiers
// that use addition are calculated
enum TYPE { NORMAL, FIRE, WATER, NATURE }
uint256[] private typeChances = [ 6, 7, 7, 7 ];
uint256 constant typeSum = 27;
// the modifier will act like a bonus for your card(s)
// NONE: no bonus will be applied
// ALL_: if all cards are of the same type, they all get
// bonus att/def/att+def numbers
// V_: if a versing card is of a certain type, your card
// will get bonus att/def numbers
// V_SWAP: this will swap the versing cards att and def
// numbers after they've been modified by any
// other active modifiers
// R_V: your card resists the type advantages of the versing card,
// normal type cards cannot receive this modifier
// A_I: your cards type advantage increases from 1.25x to 1.5x,
// normal type cards cannot receive this modifier
enum MODIFIER {
NONE,
ALL_ATT, ALL_DEF, ALL_ATT_DEF,
V_ATT, V_DEF,
V_SWAP,
R_V,
A_I
}
uint256[] private modifierChances = [
55,
5, 6, 1,
12, 14,
3,
7,
4
];
uint256 constant modifierSum = 107;
// below are the chances for the bonus stats of the modifiers,
// the seed will first choose a value between 0 and the sum, it will
// then cumulatively count up until it reaches the index with the
// matched roll
// for example;
// if your data was = [ 2, 3, 4, 2, 1 ], your cumulative total is 12,
// from there a number will be rolled and it will add up all the values
// until the cumulative total is greater than the number rolled
// if we rolled a 9, 2(0) + 3(1) + 4(2) + 2(3) = 11 > 9 so the index
// you matched in this case would be 3
// the final value will be;
// bonusMinimum + indexOf(cumulativeRoll)
uint256 constant cardBonusMinimum = 1;
uint256[] private modifierAttBonusChances = [ 2, 5, 8, 7, 3, 2, 1, 1 ]; // range: 1 - 8
uint256 constant modifierAttBonusSum = 29;
uint256[] private modifierDefBonusChances = [ 2, 3, 6, 8, 6, 5, 3, 2, 1, 1 ]; // range: 1 - 10
uint256 constant modifierDefBonusSum = 37;
// below are the distribution of the attack and defence numbers,
// in general, the attack average should be slightly higher than the
// defence average and defence should have a wider spread of values
// compared to attack which should be a tighter set of numbers
// the final value will be;
// cardMinimum + indexOf(cumulativeRoll)
uint256 constant cardAttackMinimum = 10;
uint256[] private cardAttackChances = [ 2, 2, 3, 5, 8, 9, 15, 17, 13, 11, 6, 5, 3, 2, 1, 1 ]; // range: 10 - 25
uint256 constant cardAttackSum = 103;
uint256 constant cardDefenceMinimum = 5;
uint256[] private cardDefenceChances = [ 1, 1, 2, 3, 5, 6, 11, 15, 19, 14, 12, 11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1 ]; // range: 5 - 30
uint256 constant cardDefenceSum = 153;
//////////////////////////////////////////////////////////////////////
// Registry Variables
// overall address card tracking
mapping (address => bool) _exists;
mapping (address => uint256) _indexOf;
mapping (address => address[]) _ownersOf;
mapping (address => uint256[]) _ownersClaimPriceOf;
struct AddressCard {
address _cardAddress;
uint8 _cardType;
uint8 _cardModifier;
uint8 _modifierPrimarayVal;
uint8 _modifierSecondaryVal;
uint8 _attack;
uint8 _defence;
uint8 _claimed;
uint8 _forClaim;
uint256 _lowestPrice;
address _claimContender;
}
AddressCard[] private _addressCards;
// owner and balance tracking
mapping (address => uint256) _balanceOf;
mapping (address => address[]) _cardsOf;
//////////////////////////////////////////////////////////////////////
// Events
event AddressDidEnlist(
address enlistedAddress);
event AddressCardWasWagered(
address addressCard,
address owner,
uint256 wagerAmount);
event AddressCardWagerWasCancelled(
address addressCard,
address owner);
event AddressCardWasTransferred(
address addressCard,
address fromAddress,
address toAddress);
event ClaimAttempt(
bool wasSuccessful,
address addressCard,
address claimer,
address claimContender,
address[3] claimerChoices,
address[3] claimContenderChoices,
uint256[3][2] allFinalAttackValues,
uint256[3][2] allFinalDefenceValues);
//////////////////////////////////////////////////////////////////////
// Main Functions
// start up the contract!
function AddressWarsBeta() public {
// set our dev
dev = msg.sender;
// now use the dev address as the initial seed mix
shuffleSeed(uint256(dev));
}
// any non-contract address can call this function and begin playing AddressWars!
// please note that as there are a lot of write to storage operations, this function
// will be quite expensive in terms of gas so keep that in mind when sending your
// transaction to the network!
// 350k gas should be enough to handle all of the storage operations but MetaMask
// will give a good estimate when you initialize the transaction
// in order to enlist in AddressWars, you must first pay the enlistingFee (free for beta!)
function enlist() public payable {
require(cardAddressExists(msg.sender) == false);
require(msg.value == enlistingFee);
require(msg.sender == tx.origin); // this prevents contracts from enlisting,
// only normal addresses (ie ones that can send a request) can play AddressWars.
// first shuffle the main seed with the sender address as input
uint256 tmpSeed = tmpShuffleSeed(_seed, uint256(msg.sender));
uint256 tmpModulus;
// from this point on, tmpSeed will shuffle every time tmpQuerySeed()
// is called. it is used recursively so it will mutate upon each
// call of that function and finally at the end we will update
// the overall seed to save on gas fees
// now we can query the different attributes of the card
// first lets determine the card type
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum);
uint256 cardType = cumulativeIndexOf(typeChances, tmpModulus);
// now to get the modifier
// special logic to handle normal type cards
uint256 adjustedModifierSum = modifierSum;
if (cardType == uint256(TYPE.NORMAL)) {
// normal cards cannot have the advantage increase modifier (the last in the array)
adjustedModifierSum -= modifierChances[modifierChances.length - 1];
// normal cards cannot have the resistance versing modifier (second last in the array)
adjustedModifierSum -= modifierChances[modifierChances.length - 2];
}
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, adjustedModifierSum);
uint256 cardModifier = cumulativeIndexOf(modifierChances, tmpModulus);
// now we need to find our attack and defence values
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardAttackSum);
uint256 cardAttack = cardAttackMinimum + cumulativeIndexOf(cardAttackChances, tmpModulus);
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardDefenceSum);
uint256 cardDefence = cardDefenceMinimum + cumulativeIndexOf(cardDefenceChances, tmpModulus);
// finally handle our modifier values
uint256 primaryModifierVal = 0;
uint256 secondaryModifierVal = 0;
uint256 bonusAttackPenalty = 0;
uint256 bonusDefencePenalty = 0;
// handle the logic of our modifiers
if (cardModifier == uint256(MODIFIER.ALL_ATT)) { // all of the same type attack bonus
// the primary modifier value will hold our attack bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
// now for the attack penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
// penalty is doubled
bonusAttackPenalty *= 2;
} else if (cardModifier == uint256(MODIFIER.ALL_DEF)) { // all of the same type defence bonus
// the primary modifier value will hold our defence bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
// now for the defence penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
// penalty is doubled
bonusDefencePenalty *= 2;
} else if (cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) { // all of the same type attack and defence bonus
// the primary modifier value will hold our attack bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
primaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
// now for the attack penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
// penalty is doubled
bonusAttackPenalty *= 2;
// the secondary modifier value will hold our defence bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
// now for the defence penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
// penalty is doubled
bonusDefencePenalty *= 2;
} else if (cardModifier == uint256(MODIFIER.V_ATT)) { // versing a certain type attack bonus
// the primary modifier value will hold type we need to verse in order to get our bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum);
primaryModifierVal = cumulativeIndexOf(typeChances, tmpModulus);
// the secondary modifier value will hold our attack bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
// now for the attack penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierAttBonusSum);
bonusAttackPenalty = cardBonusMinimum + cumulativeIndexOf(modifierAttBonusChances, tmpModulus);
} else if (cardModifier == uint256(MODIFIER.V_DEF)) { // versing a certain type defence bonus
// the primary modifier value will hold type we need to verse in order to get our bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, typeSum);
primaryModifierVal = cumulativeIndexOf(typeChances, tmpModulus);
// the secondary modifier value will hold our defence bonus
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
secondaryModifierVal = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
// now for the defence penalty
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, modifierDefBonusSum);
bonusDefencePenalty = cardBonusMinimum + cumulativeIndexOf(modifierDefBonusChances, tmpModulus);
}
// now apply the penalties
if (bonusAttackPenalty >= cardAttack) {
cardAttack = 0;
} else {
cardAttack -= bonusAttackPenalty;
}
if (bonusDefencePenalty >= cardDefence) {
cardDefence = 0;
} else {
cardDefence -= bonusDefencePenalty;
}
// now to add it to the registry
_exists[msg.sender] = true;
_indexOf[msg.sender] = uint256(_addressCards.length);
_ownersOf[msg.sender] = [ msg.sender ];
_ownersClaimPriceOf[msg.sender] = [ uint256(0) ];
_addressCards.push(AddressCard({
_cardAddress: msg.sender,
_cardType: uint8(cardType),
_cardModifier: uint8(cardModifier),
_modifierPrimarayVal: uint8(primaryModifierVal),
_modifierSecondaryVal: uint8(secondaryModifierVal),
_attack: uint8(cardAttack),
_defence: uint8(cardDefence),
_claimed: uint8(0),
_forClaim: uint8(0),
_lowestPrice: uint256(0),
_claimContender: address(0)
}));
// ...and now start your own collection!
_cardsOf[msg.sender] = [ msg.sender ];
// dev receives the enlisting fee
_balanceOf[dev] = SafeMath.add(_balanceOf[dev], enlistingFee);
// finally we need to update the main seed and as we initially started with
// the current main seed, tmpSeed will be the current representation of the seed
_seed = tmpSeed;
// now that we're done, it's time to log the event
AddressDidEnlist(msg.sender);
}
// this is where you can wager one of your addresses for a certain amount.
// any other player can then attempt to claim your address off you, if the
// address is your own address, you will simply give them a copy (limited to 10
// total copies) but otherwise the player will take that address off you if they
// are successful.
// here's what can happen when you wager;
// 1. if an opponent is successful in claiming your card, they will receive 50%
// of the wager amount back, the dev gets 2% and you get 48%
// 2. if an opponent is unsuccessful in claiming your card, you will receive
// 98% of the wager amount and the dev will get 2%
// 3. if an opponent is draws with you when claiming your card, they will receive
// 98% of the wager amount back and the dev will get 2%
// your wager will remain available for anyone to claim up until either you cancel
// the wager or an opponent is successful in claiming your card
// in order to wager in AddressWars, you must first pay the wageringFee (free for beta!)
function wagerCardForAmount(address cardAddress, uint256 amount) public payable {
require(amount > 0);
require(cardAddressExists(msg.sender));
require(msg.value == wageringFee);
uint256 firstMatchedIndex;
bool isAlreadyWagered;
(firstMatchedIndex, isAlreadyWagered, , , ) = getOwnerOfCardsCheapestWager(msg.sender, cardAddress);
// calling the above method will automatically reinforce the check that the cardAddress exists
// as well as the sender actually owning the card
// we cannot wager a card if we are already wagering it
require(isAlreadyWagered == false);
// double check to make sure the card is actually owned by the sender
require(msg.sender == _ownersOf[cardAddress][firstMatchedIndex]);
AddressCard memory addressCardForWager = _addressCards[_indexOf[cardAddress]];
if (msg.sender == cardAddress) {
// we need to enforce the claim limit if you are the initial owner
require(addressCardForWager._claimed < CLAIM_LIMIT);
}
// now write the new data
_ownersClaimPriceOf[cardAddress][firstMatchedIndex] = amount;
// now update our statistics
updateCardStatistics(cardAddress);
// dev receives the wagering fee
_balanceOf[dev] = SafeMath.add(_balanceOf[dev], wageringFee);
// now that we're done, it's time to log the event
AddressCardWasWagered(cardAddress, msg.sender, amount);
}
function cancelWagerOfCard(address cardAddress) public {
require(cardAddressExists(msg.sender));
uint256 firstMatchedIndex;
bool isAlreadyWagered;
(firstMatchedIndex, isAlreadyWagered, , , ) = getOwnerOfCardsCheapestWager(msg.sender, cardAddress);
// calling the above method will automatically reinforce the check that the cardAddress exists
// as well as the owner actually owning the card
// we can only cancel a wager if there already is one
require(isAlreadyWagered);
// double check to make sure the card is actually owned by the sender
require(msg.sender == _ownersOf[cardAddress][firstMatchedIndex]);
// now write the new data
_ownersClaimPriceOf[cardAddress][firstMatchedIndex] = 0;
// now update our statistics
updateCardStatistics(cardAddress);
// now that we're done, it's time to log the event
AddressCardWagerWasCancelled(cardAddress, msg.sender);
}
// this is the main battle function of the contract, it takes the card address you
// wish to claim as well as your card choices as input. a lot of complex calculations
// happen within this function and in the end, a result will be determined on whether
// you won the claim or not. at the end, an event will be logged with all of the information
// about what happened in the battle including the final result, the contenders,
// the card choices (yours and your opponenets) as well as the final attack and defence numbers.
// this function will revert if the msg.value does not match the current minimum claim value
// of the card address you are attempting to claim.
function attemptToClaimCard(address cardAddress, address[3] choices) public payable {
// a lot of the functionality of attemptToClaimCard() is calculated in other methods as
// there is only a 16 local variable limit per method and we need a lot more than that
// see ownerCanClaimCard() below, this ensures we can actually claim the card we are after
// by running through various requirement checks
address claimContender;
uint256 claimContenderIndex;
(claimContender, claimContenderIndex) = ownerCanClaimCard(msg.sender, cardAddress, choices, msg.value);
address[3] memory opponentCardChoices = generateCardsFromClaimForOpponent(cardAddress, claimContender);
uint256[3][2] memory allFinalAttackFigures;
uint256[3][2] memory allFinalDefenceFigures;
(allFinalAttackFigures, allFinalDefenceFigures) = calculateAdjustedFiguresForBattle(choices, opponentCardChoices);
// after this point we have all of the modified attack and defence figures
// in the arrays above. the way the winner is determined is by counting
// how many attack points get through in total for each card, this is
// calculated by simply doing;
// opponentsHits = yourCard[attack] - opponentsCard[defence]
// if the defence of the opposing card is greater than the attack value,
// no hits will be taken.
// at the end, all hits are added up and the winner is the one with
// the least total amount of hits, if it is a draw, the wager will be
// returned to the sender (minus the dev fee)
uint256[2] memory totalHits = [ uint256(0), uint256(0) ];
for (uint256 i = 0; i < 3; i++) {
// start with the opponent attack to you
totalHits[0] += (allFinalAttackFigures[1][i] > allFinalDefenceFigures[0][i] ? allFinalAttackFigures[1][i] - allFinalDefenceFigures[0][i] : 0);
// then your attack to the opponent
totalHits[1] += (allFinalAttackFigures[0][i] > allFinalDefenceFigures[1][i] ? allFinalAttackFigures[0][i] - allFinalDefenceFigures[1][i] : 0);
}
// before we process the outcome, we should log the event.
// order is important here as we should log a successful
// claim attempt then a transfer (if that's what happens)
// instead of the other way around
ClaimAttempt(
totalHits[0] < totalHits[1], // it was successful if we had less hits than the opponent
cardAddress,
msg.sender,
claimContender,
choices,
opponentCardChoices,
allFinalAttackFigures,
allFinalDefenceFigures
);
// handle the outcomes
uint256 tmpAmount;
if (totalHits[0] == totalHits[1]) { // we have a draw
// hand out the dev tax
tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2%
_balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount);
// now we return the rest to the sender
_balanceOf[msg.sender] = SafeMath.add(_balanceOf[msg.sender], SafeMath.sub(msg.value, tmpAmount)); // 98%
} else if (totalHits[0] > totalHits[1]) { // we have more hits so we were unsuccessful
// hand out the dev tax
tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2%
_balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount);
// now we give the rest to the claim contender
_balanceOf[claimContender] = SafeMath.add(_balanceOf[claimContender], SafeMath.sub(msg.value, tmpAmount)); // 98%
} else { // this means we have less hits than the opponent so we were successful in our claim!
// hand out the dev tax
tmpAmount = SafeMath.div(SafeMath.mul(msg.value, devTax), 100); // 2%
_balanceOf[dev] = SafeMath.add(_balanceOf[dev], tmpAmount);
// return half to the sender
_balanceOf[msg.sender] = SafeMath.add(_balanceOf[msg.sender], SafeMath.div(msg.value, 2)); // 50%
// and now the remainder goes to the claim contender
_balanceOf[claimContender] = SafeMath.add(_balanceOf[claimContender], SafeMath.sub(SafeMath.div(msg.value, 2), tmpAmount)); // 48%
// finally transfer the ownership of the card from the claim contender to the sender but
// first we need to make sure to cancel the wager
_ownersClaimPriceOf[cardAddress][claimContenderIndex] = 0;
transferCard(cardAddress, claimContender, msg.sender);
// now update our statistics
updateCardStatistics(cardAddress);
}
}
function transferCardTo(address cardAddress, address toAddress) public {
// you can view this internal method below for more details.
// all of the requirements around transferring a card are
// tested within the transferCard() method.
// you are free to gift your own address card to anyone
// (assuming there are less than 10 copies circulating).
transferCard(cardAddress, msg.sender, toAddress);
}
//////////////////////////////////////////////////////////////////////
// Wallet Functions
function withdrawAmount(uint256 amount) public {
require(amount > 0);
address sender = msg.sender;
uint256 balance = _balanceOf[sender];
require(amount <= balance);
// transfer and update the balances
_balanceOf[sender] = SafeMath.sub(_balanceOf[sender], amount);
sender.transfer(amount);
}
function withdrawAll() public {
address sender = msg.sender;
uint256 balance = _balanceOf[sender];
require(balance > 0);
// transfer and update the balances
_balanceOf[sender] = 0;
sender.transfer(balance);
}
function getBalanceOfSender() public view returns (uint256) {
return _balanceOf[msg.sender];
}
//////////////////////////////////////////////////////////////////////
// Helper Functions
function tmpShuffleSeed(uint256 tmpSeed, uint256 mix) public view returns (uint256) {
// really mix it up!
uint256 newTmpSeed = tmpSeed;
uint256 currentTime = now;
uint256 timeMix = currentTime + mix;
// in this instance, overflow is ok as we are just shuffling around the bits
// first lets square the seed
newTmpSeed *= newTmpSeed;
// now add our time and mix
newTmpSeed += timeMix;
// multiply by the time
newTmpSeed *= currentTime;
// now add our mix
newTmpSeed += mix;
// and finally multiply by the time and mix
newTmpSeed *= timeMix;
return newTmpSeed;
}
function shuffleSeed(uint256 mix) private {
// set our seed based on our last seed
_seed = tmpShuffleSeed(_seed, mix);
}
function tmpQuerySeed(uint256 tmpSeed, uint256 modulus) public view returns (uint256 tmpShuffledSeed, uint256 result) {
require(modulus > 0);
// get our answer
uint256 response = tmpSeed % modulus;
// now we want to re-mix our seed based off our response
uint256 mix = response + 1; // non-zero
mix *= modulus;
mix += response;
mix *= modulus;
// now return it
return (tmpShuffleSeed(tmpSeed, mix), response);
}
function querySeed(uint256 modulus) private returns (uint256) {
require(modulus > 0);
uint256 tmpSeed;
uint256 response;
(tmpSeed, response) = tmpQuerySeed(_seed, modulus);
// tmpSeed will now represent the suffled version of our last seed
_seed = tmpSeed;
// now return it
return response;
}
function cumulativeIndexOf(uint256[] array, uint256 target) private pure returns (uint256) {
bool hasFound = false;
uint256 index;
uint256 cumulativeTotal = 0;
for (uint256 i = 0; i < array.length; i++) {
cumulativeTotal += array[i];
if (cumulativeTotal > target) {
hasFound = true;
index = i;
break;
}
}
require(hasFound);
return index;
}
function cardAddressExists(address cardAddress) public view returns (bool) {
return _exists[cardAddress];
}
function indexOfCardAddress(address cardAddress) public view returns (uint256) {
require(cardAddressExists(cardAddress));
return _indexOf[cardAddress];
}
function ownerCountOfCard(address owner, address cardAddress) public view returns (uint256) {
// both card addresses need to exist in order to own cards
require(cardAddressExists(owner));
require(cardAddressExists(cardAddress));
// check if it's your own address
if (owner == cardAddress) {
return 0;
}
uint256 ownerCount = 0;
address[] memory owners = _ownersOf[cardAddress];
for (uint256 i = 0; i < owners.length; i++) {
if (owner == owners[i]) {
ownerCount++;
}
}
return ownerCount;
}
function ownerHasCard(address owner, address cardAddress) public view returns (bool doesOwn, uint256[] indexes) {
// both card addresses need to exist in order to own cards
require(cardAddressExists(owner));
require(cardAddressExists(cardAddress));
uint256[] memory ownerIndexes = new uint256[](ownerCountOfCard(owner, cardAddress));
// check if it's your own address
if (owner == cardAddress) {
return (true, ownerIndexes);
}
if (ownerIndexes.length > 0) {
uint256 currentIndex = 0;
address[] memory owners = _ownersOf[cardAddress];
for (uint256 i = 0; i < owners.length; i++) {
if (owner == owners[i]) {
ownerIndexes[currentIndex] = i;
currentIndex++;
}
}
}
// this owner may own multiple copies of the card and so an array of indexes are returned
// if the owner does not own the card, it will return (false, [])
return (ownerIndexes.length > 0, ownerIndexes);
}
function ownerHasCardSimple(address owner, address cardAddress) private view returns (bool) {
bool doesOwn;
(doesOwn, ) = ownerHasCard(owner, cardAddress);
return doesOwn;
}
function ownerCanClaimCard(address owner, address cardAddress, address[3] choices, uint256 amount) private view returns (address currentClaimContender, uint256 claimContenderIndex) {
// you cannot claim back your own address cards
require(owner != cardAddress);
require(cardAddressExists(owner));
require(ownerHasCardSimple(owner, cardAddress) || _cardsOf[owner].length < MAX_UNIQUE_CARDS_PER_ADDRESS);
uint256 cheapestIndex;
bool canClaim;
address claimContender;
uint256 lowestClaimPrice;
(cheapestIndex, canClaim, claimContender, lowestClaimPrice, ) = getCheapestCardWager(cardAddress);
// make sure we can actually claim it and that we are paying the correct amount
require(canClaim);
require(amount == lowestClaimPrice);
// we also need to check that the sender is not the current claim contender
require(owner != claimContender);
// now check if we own all of our choices
for (uint256 i = 0; i < choices.length; i++) {
require(ownerHasCardSimple(owner, choices[i])); // if one is not owned, it will trigger a revert
}
// if no requires have been triggered by this point it means we are able to claim the card
// now return the claim contender and their index
return (claimContender, cheapestIndex);
}
function generateCardsFromClaimForOpponent(address cardAddress, address opponentAddress) private returns (address[3]) {
require(cardAddressExists(cardAddress));
require(cardAddressExists(opponentAddress));
require(ownerHasCardSimple(opponentAddress, cardAddress));
// generate the opponents cards from their own inventory
// it is important to note that at least 1 of their choices
// needs to be the card you are attempting to claim
address[] memory cardsOfOpponent = _cardsOf[opponentAddress];
address[3] memory opponentCardChoices;
uint256 tmpSeed = tmpShuffleSeed(_seed, uint256(opponentAddress));
uint256 tmpModulus;
uint256 indexOfClaimableCard;
(tmpSeed, indexOfClaimableCard) = tmpQuerySeed(tmpSeed, 3); // 0, 1 or 2
for (uint256 i = 0; i < 3; i++) {
if (i == indexOfClaimableCard) {
opponentCardChoices[i] = cardAddress;
} else {
(tmpSeed, tmpModulus) = tmpQuerySeed(tmpSeed, cardsOfOpponent.length);
opponentCardChoices[i] = cardsOfOpponent[tmpModulus];
}
}
// finally we need to update the main seed and as we initially started with
// the current main seed, tmpSeed will be the current representation of the seed
_seed = tmpSeed;
return opponentCardChoices;
}
function updateCardStatistics(address cardAddress) private {
AddressCard storage addressCardClaimed = _addressCards[_indexOf[cardAddress]];
address claimContender;
uint256 lowestClaimPrice;
uint256 wagerCount;
( , , claimContender, lowestClaimPrice, wagerCount) = getCheapestCardWager(cardAddress);
addressCardClaimed._forClaim = uint8(wagerCount);
addressCardClaimed._lowestPrice = lowestClaimPrice;
addressCardClaimed._claimContender = claimContender;
}
function transferCard(address cardAddress, address fromAddress, address toAddress) private {
require(toAddress != fromAddress);
require(cardAddressExists(cardAddress));
require(cardAddressExists(fromAddress));
uint256 firstMatchedIndex;
bool isWagered;
(firstMatchedIndex, isWagered, , , ) = getOwnerOfCardsCheapestWager(fromAddress, cardAddress);
require(isWagered == false); // you cannot transfer a card if it's currently wagered
require(cardAddressExists(toAddress));
require(toAddress != cardAddress); // can't transfer a card to it's original address
require(ownerHasCardSimple(toAddress, cardAddress) || _cardsOf[toAddress].length < MAX_UNIQUE_CARDS_PER_ADDRESS);
// firstly, if toAddress doesn't have a copy we need to add one
if (!ownerHasCardSimple(toAddress, cardAddress)) {
_cardsOf[toAddress].push(cardAddress);
}
// now check whether the fromAddress is just our original card
// address, if this is the case, they are free to transfer out
// one of their cards assuming the claim limit is not yet reached
if (fromAddress == cardAddress) { // the card is being claimed/gifted
AddressCard storage addressCardClaimed = _addressCards[_indexOf[cardAddress]];
require(addressCardClaimed._claimed < CLAIM_LIMIT);
// we need to push new data to our arrays
_ownersOf[cardAddress].push(toAddress);
_ownersClaimPriceOf[cardAddress].push(uint256(0));
// now update the claimed count in the registry
addressCardClaimed._claimed = uint8(_ownersOf[cardAddress].length - 1); // we exclude the original address
} else {
// firstly we need to cache the current index from our fromAddress' _cardsOf
uint256 cardIndexOfSender = getCardIndexOfOwner(cardAddress, fromAddress);
// now just update the address at the firstMatchedIndex
_ownersOf[cardAddress][firstMatchedIndex] = toAddress;
// finally check if our fromAddress has any copies of the card left
if (!ownerHasCardSimple(fromAddress, cardAddress)) {
// if not delete that card from their inventory and make room in the array
for (uint256 i = cardIndexOfSender; i < _cardsOf[fromAddress].length - 1; i++) {
// shuffle the next value over
_cardsOf[fromAddress][i] = _cardsOf[fromAddress][i + 1];
}
// now decrease the length
_cardsOf[fromAddress].length--;
}
}
// now that we're done, it's time to log the event
AddressCardWasTransferred(cardAddress, fromAddress, toAddress);
}
function calculateAdjustedFiguresForBattle(address[3] yourChoices, address[3] opponentsChoices) private view returns (uint256[3][2] allAdjustedAttackFigures, uint256[3][2] allAdjustedDefenceFigures) {
// [0] is yours, [1] is your opponents
AddressCard[3][2] memory allCards;
uint256[3][2] memory allAttackFigures;
uint256[3][2] memory allDefenceFigures;
bool[2] memory allOfSameType = [ true, true ];
uint256[2] memory cumulativeAttackBonuses = [ uint256(0), uint256(0) ];
uint256[2] memory cumulativeDefenceBonuses = [ uint256(0), uint256(0) ];
for (uint256 i = 0; i < 3; i++) {
// cache your cards
require(_exists[yourChoices[i]]);
allCards[0][i] = _addressCards[_indexOf[yourChoices[i]]];
allAttackFigures[0][i] = allCards[0][i]._attack;
allDefenceFigures[0][i] = allCards[0][i]._defence;
// cache your opponents cards
require(_exists[opponentsChoices[i]]);
allCards[1][i] = _addressCards[_indexOf[opponentsChoices[i]]];
allAttackFigures[1][i] = allCards[1][i]._attack;
allDefenceFigures[1][i] = allCards[1][i]._defence;
}
// for the next part, order is quite important as we want the
// addition to happen first and then the multiplication to happen
// at the very end for the type advantages/resistances
//////////////////////////////////////////////////////////////
// the first modifiers that needs to be applied is the
// ALL_ATT, ALL_DEF and the ALL_ATT_DEF mod
// if all 3 of the chosen cards match the same type
// and if at least one of them have the ALL_ATT, ALL_DEF
// or ALL_ATT_DEF modifier, all of the cards will receive
// the cumulative bonus for att/def/att+def
for (i = 0; i < 3; i++) {
// start with your cards
// compare to see if the types are the same as the previous one
if (i > 0 && allCards[0][i]._cardType != allCards[0][i - 1]._cardType) {
allOfSameType[0] = false;
}
// next count up all the modifier values for a total possible bonus
if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_ATT)) { // all attack
// for the ALL_ATT modifier, the additional attack bonus is
// stored in the primary value
cumulativeAttackBonuses[0] += allCards[0][i]._modifierPrimarayVal;
} else if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_DEF)) { // all defence
// for the ALL_DEF modifier, the additional defence bonus is
// stored in the primary value
cumulativeDefenceBonuses[0] += allCards[0][i]._modifierPrimarayVal;
} else if (allCards[0][i]._cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) { // all attack + defence
// for the ALL_ATT_DEF modifier, the additional attack bonus is
// stored in the primary value and the additional defence bonus is
// stored in the secondary value
cumulativeAttackBonuses[0] += allCards[0][i]._modifierPrimarayVal;
cumulativeDefenceBonuses[0] += allCards[0][i]._modifierSecondaryVal;
}
// now do the same for your opponent
if (i > 0 && allCards[1][i]._cardType != allCards[1][i - 1]._cardType) {
allOfSameType[1] = false;
}
if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_ATT)) {
cumulativeAttackBonuses[1] += allCards[1][i]._modifierPrimarayVal;
} else if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_DEF)) {
cumulativeDefenceBonuses[1] += allCards[1][i]._modifierPrimarayVal;
} else if (allCards[1][i]._cardModifier == uint256(MODIFIER.ALL_ATT_DEF)) {
cumulativeAttackBonuses[1] += allCards[1][i]._modifierPrimarayVal;
cumulativeDefenceBonuses[1] += allCards[1][i]._modifierSecondaryVal;
}
}
// we void our bonus if they aren't all of the type
if (!allOfSameType[0]) {
cumulativeAttackBonuses[0] = 0;
cumulativeDefenceBonuses[0] = 0;
}
if (!allOfSameType[1]) {
cumulativeAttackBonuses[1] = 0;
cumulativeDefenceBonuses[1] = 0;
}
// now add the bonus figures to the initial attack numbers, they will be 0
// if they either weren't all of the same type or if no cards actually had
// the ALL_ modifier
for (i = 0; i < 3; i++) {
// for your cards
allAttackFigures[0][i] += cumulativeAttackBonuses[0];
allDefenceFigures[0][i] += cumulativeDefenceBonuses[0];
// ...and your opponents cards
allAttackFigures[1][i] += cumulativeAttackBonuses[1];
allDefenceFigures[1][i] += cumulativeDefenceBonuses[1];
}
//////////////////////////////////////////////////////////////
// the second modifier that needs to be applied is the V_ATT
// or the V_DEF mod
// if the versing card matches the same type listed in the
// primaryModifierVal, that card will receive the bonus in
// secondaryModifierVal for att/def
for (i = 0; i < 3; i++) {
// start with your cards
if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_ATT)) { // versing attack
// check if the versing cards type matches the primary value
if (allCards[1][i]._cardType == allCards[0][i]._modifierPrimarayVal) {
// add the attack bonus (amount is held in the secondary value)
allAttackFigures[0][i] += allCards[0][i]._modifierSecondaryVal;
}
} else if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_DEF)) { // versing defence
// check if the versing cards type matches the primary value
if (allCards[1][i]._cardType == allCards[0][i]._modifierPrimarayVal) {
// add the defence bonus (amount is held in the secondary value)
allDefenceFigures[0][i] += allCards[0][i]._modifierSecondaryVal;
}
}
// now do the same for your opponent
if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_ATT)) {
if (allCards[0][i]._cardType == allCards[1][i]._modifierPrimarayVal) {
allAttackFigures[1][i] += allCards[1][i]._modifierSecondaryVal;
}
} else if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_DEF)) {
if (allCards[0][i]._cardType == allCards[1][i]._modifierPrimarayVal) {
allDefenceFigures[1][i] += allCards[1][i]._modifierSecondaryVal;
}
}
}
//////////////////////////////////////////////////////////////
// the third modifier that needs to be applied is the type
// advantage numbers as well as applying R_V (resists versing
// cards type advantage) and A_I (increases your cards advantage)
for (i = 0; i < 3; i++) {
// start with your cards
// first check if the card we're versing resists our type advantage
if (allCards[1][i]._cardModifier != uint256(MODIFIER.R_V)) {
// test all the possible combinations of advantages
if (
// fire vs nature
(allCards[0][i]._cardType == uint256(TYPE.FIRE) && allCards[1][i]._cardType == uint256(TYPE.NATURE)) ||
// water vs fire
(allCards[0][i]._cardType == uint256(TYPE.WATER) && allCards[1][i]._cardType == uint256(TYPE.FIRE)) ||
// nature vs water
(allCards[0][i]._cardType == uint256(TYPE.NATURE) && allCards[1][i]._cardType == uint256(TYPE.WATER))
) {
// now check if your card has a type advantage increase modifier
if (allCards[0][i]._cardModifier != uint256(MODIFIER.A_I)) {
allAttackFigures[0][i] = SafeMath.div(SafeMath.mul(allAttackFigures[0][i], 3), 2); // x1.5
allDefenceFigures[0][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[0][i], 3), 2); // x1.5
} else {
allAttackFigures[0][i] = SafeMath.div(SafeMath.mul(allAttackFigures[0][i], 5), 4); // x1.25
allDefenceFigures[0][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[0][i], 5), 4); // x1.25
}
}
}
// now do the same for your opponent
if (allCards[0][i]._cardModifier != uint256(MODIFIER.R_V)) {
if (
(allCards[1][i]._cardType == uint256(TYPE.FIRE) && allCards[0][i]._cardType == uint256(TYPE.NATURE)) ||
(allCards[1][i]._cardType == uint256(TYPE.WATER) && allCards[0][i]._cardType == uint256(TYPE.FIRE)) ||
(allCards[1][i]._cardType == uint256(TYPE.NATURE) && allCards[0][i]._cardType == uint256(TYPE.WATER))
) {
if (allCards[1][i]._cardModifier != uint256(MODIFIER.A_I)) {
allAttackFigures[1][i] = SafeMath.div(SafeMath.mul(allAttackFigures[1][i], 3), 2); // x1.5
allDefenceFigures[1][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[1][i], 3), 2); // x1.5
} else {
allAttackFigures[1][i] = SafeMath.div(SafeMath.mul(allAttackFigures[1][i], 5), 4); // x1.25
allDefenceFigures[1][i] = SafeMath.div(SafeMath.mul(allDefenceFigures[1][i], 5), 4); // x1.25
}
}
}
}
//////////////////////////////////////////////////////////////
// the final modifier that needs to be applied is the V_SWAP mod
// if your card has this modifier, it will swap the final attack
// and defence numbers of your card
uint256 tmp;
for (i = 0; i < 3; i++) {
// start with your cards
// check if the versing card has the V_SWAP modifier
if (allCards[1][i]._cardModifier == uint256(MODIFIER.V_SWAP)) {
tmp = allAttackFigures[0][i];
allAttackFigures[0][i] = allDefenceFigures[0][i];
allDefenceFigures[0][i] = tmp;
}
// ...and your opponents cards
if (allCards[0][i]._cardModifier == uint256(MODIFIER.V_SWAP)) {
tmp = allAttackFigures[1][i];
allAttackFigures[1][i] = allDefenceFigures[1][i];
allDefenceFigures[1][i] = tmp;
}
}
// we're all done!
return (allAttackFigures, allDefenceFigures);
}
//////////////////////////////////////////////////////////////////////
// Getter Functions
function getCard(address cardAddress) public view returns (uint256 cardIndex, uint256 cardType, uint256 cardModifier, uint256 cardModifierPrimaryVal, uint256 cardModifierSecondaryVal, uint256 attack, uint256 defence, uint256 claimed, uint256 forClaim, uint256 lowestPrice, address claimContender) {
require(cardAddressExists(cardAddress));
uint256 index = _indexOf[cardAddress];
AddressCard memory addressCard = _addressCards[index];
return (
index,
uint256(addressCard._cardType),
uint256(addressCard._cardModifier),
uint256(addressCard._modifierPrimarayVal),
uint256(addressCard._modifierSecondaryVal),
uint256(addressCard._attack),
uint256(addressCard._defence),
uint256(addressCard._claimed),
uint256(addressCard._forClaim),
uint256(addressCard._lowestPrice),
address(addressCard._claimContender)
);
}
function getCheapestCardWager(address cardAddress) public view returns (uint256 cheapestIndex, bool isClaimable, address claimContender, uint256 claimPrice, uint256 wagerCount) {
require(cardAddressExists(cardAddress));
uint256 cheapestSale = 0;
uint256 indexOfCheapestSale = 0;
uint256 totalWagers = 0;
uint256[] memory allOwnersClaimPrice = _ownersClaimPriceOf[cardAddress];
for (uint256 i = 0; i < allOwnersClaimPrice.length; i++) {
uint256 priceAtIndex = allOwnersClaimPrice[i];
if (priceAtIndex != 0) {
totalWagers++;
if (cheapestSale == 0 || priceAtIndex < cheapestSale) {
cheapestSale = priceAtIndex;
indexOfCheapestSale = i;
}
}
}
return (
indexOfCheapestSale,
(cheapestSale > 0),
(cheapestSale > 0 ? _ownersOf[cardAddress][indexOfCheapestSale] : address(0)),
cheapestSale,
totalWagers
);
}
function getOwnerOfCardsCheapestWager(address owner, address cardAddress) public view returns (uint256 cheapestIndex, bool isSelling, uint256 claimPrice, uint256 priceRank, uint256 outOf) {
bool doesOwn;
uint256[] memory indexes;
(doesOwn, indexes) = ownerHasCard(owner, cardAddress);
require(doesOwn);
uint256[] memory allOwnersClaimPrice = _ownersClaimPriceOf[cardAddress];
uint256 cheapestSale = 0;
uint256 indexOfCheapestSale = 0; // this will handle the case of owner == cardAddress
if (indexes.length > 0) {
indexOfCheapestSale = indexes[0]; // defaults to the first index matched
} else { // also will handle the case of owner == cardAddress
cheapestSale = allOwnersClaimPrice[0];
}
for (uint256 i = 0; i < indexes.length; i++) {
if (allOwnersClaimPrice[indexes[i]] != 0 && (cheapestSale == 0 || allOwnersClaimPrice[indexes[i]] < cheapestSale)) {
cheapestSale = allOwnersClaimPrice[indexes[i]];
indexOfCheapestSale = indexes[i];
}
}
uint256 saleRank = 0;
uint256 totalWagers = 0;
if (cheapestSale > 0) {
saleRank = 1;
for (i = 0; i < allOwnersClaimPrice.length; i++) {
if (allOwnersClaimPrice[i] != 0) {
totalWagers++;
if (allOwnersClaimPrice[i] < cheapestSale) {
saleRank++;
}
}
}
}
return (
indexOfCheapestSale,
(cheapestSale > 0),
cheapestSale,
saleRank,
totalWagers
);
}
function getCardIndexOfOwner(address cardAddress, address owner) public view returns (uint256) {
require(cardAddressExists(cardAddress));
require(cardAddressExists(owner));
require(ownerHasCardSimple(owner, cardAddress));
uint256 matchedIndex;
address[] memory cardsOfOwner = _cardsOf[owner];
for (uint256 i = 0; i < cardsOfOwner.length; i++) {
if (cardsOfOwner[i] == cardAddress) {
matchedIndex = i;
break;
}
}
return matchedIndex;
}
function getTotalUniqueCards() public view returns (uint256) {
return _addressCards.length;
}
function getAllCardsAddress() public view returns (bytes20[]) {
bytes20[] memory allCardsAddress = new bytes20[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsAddress[i] = bytes20(addressCard._cardAddress);
}
return allCardsAddress;
}
function getAllCardsType() public view returns (bytes1[]) {
bytes1[] memory allCardsType = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsType[i] = bytes1(addressCard._cardType);
}
return allCardsType;
}
function getAllCardsModifier() public view returns (bytes1[]) {
bytes1[] memory allCardsModifier = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsModifier[i] = bytes1(addressCard._cardModifier);
}
return allCardsModifier;
}
function getAllCardsModifierPrimaryVal() public view returns (bytes1[]) {
bytes1[] memory allCardsModifierPrimaryVal = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsModifierPrimaryVal[i] = bytes1(addressCard._modifierPrimarayVal);
}
return allCardsModifierPrimaryVal;
}
function getAllCardsModifierSecondaryVal() public view returns (bytes1[]) {
bytes1[] memory allCardsModifierSecondaryVal = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsModifierSecondaryVal[i] = bytes1(addressCard._modifierSecondaryVal);
}
return allCardsModifierSecondaryVal;
}
function getAllCardsAttack() public view returns (bytes1[]) {
bytes1[] memory allCardsAttack = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsAttack[i] = bytes1(addressCard._attack);
}
return allCardsAttack;
}
function getAllCardsDefence() public view returns (bytes1[]) {
bytes1[] memory allCardsDefence = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsDefence[i] = bytes1(addressCard._defence);
}
return allCardsDefence;
}
function getAllCardsClaimed() public view returns (bytes1[]) {
bytes1[] memory allCardsClaimed = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsClaimed[i] = bytes1(addressCard._claimed);
}
return allCardsClaimed;
}
function getAllCardsForClaim() public view returns (bytes1[]) {
bytes1[] memory allCardsForClaim = new bytes1[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsForClaim[i] = bytes1(addressCard._forClaim);
}
return allCardsForClaim;
}
function getAllCardsLowestPrice() public view returns (bytes32[]) {
bytes32[] memory allCardsLowestPrice = new bytes32[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsLowestPrice[i] = bytes32(addressCard._lowestPrice);
}
return allCardsLowestPrice;
}
function getAllCardsClaimContender() public view returns (bytes4[]) {
// returns the indexes of the claim contender
bytes4[] memory allCardsClaimContender = new bytes4[](_addressCards.length);
for (uint256 i = 0; i < _addressCards.length; i++) {
AddressCard memory addressCard = _addressCards[i];
allCardsClaimContender[i] = bytes4(_indexOf[addressCard._claimContender]);
}
return allCardsClaimContender;
}
function getAllOwnersOfCard(address cardAddress) public view returns (bytes4[]) {
require(cardAddressExists(cardAddress));
// returns the indexes of the owners
address[] memory ownersOfCardAddress = _ownersOf[cardAddress];
bytes4[] memory allOwners = new bytes4[](ownersOfCardAddress.length);
for (uint256 i = 0; i < ownersOfCardAddress.length; i++) {
allOwners[i] = bytes4(_indexOf[ownersOfCardAddress[i]]);
}
return allOwners;
}
function getAllOwnersClaimPriceOfCard(address cardAddress) public view returns (bytes32[]) {
require(cardAddressExists(cardAddress));
uint256[] memory ownersClaimPriceOfCardAddress = _ownersClaimPriceOf[cardAddress];
bytes32[] memory allOwnersClaimPrice = new bytes32[](ownersClaimPriceOfCardAddress.length);
for (uint256 i = 0; i < ownersClaimPriceOfCardAddress.length; i++) {
allOwnersClaimPrice[i] = bytes32(ownersClaimPriceOfCardAddress[i]);
}
return allOwnersClaimPrice;
}
function getAllCardAddressesOfOwner(address owner) public view returns (bytes4[]) {
require(cardAddressExists(owner));
// returns the indexes of the cards owned
address[] memory cardsOfOwner = _cardsOf[owner];
bytes4[] memory allCardAddresses = new bytes4[](cardsOfOwner.length);
for (uint256 i = 0; i < cardsOfOwner.length; i++) {
allCardAddresses[i] = bytes4(_indexOf[cardsOfOwner[i]]);
}
return allCardAddresses;
}
function getAllCardAddressesCountOfOwner(address owner) public view returns (bytes1[]) {
require(cardAddressExists(owner));
address[] memory cardsOfOwner = _cardsOf[owner];
bytes1[] memory allCardAddressesCount = new bytes1[](cardsOfOwner.length);
for (uint256 i = 0; i < cardsOfOwner.length; i++) {
allCardAddressesCount[i] = bytes1(ownerCountOfCard(owner, cardsOfOwner[i]));
}
return allCardAddressesCount;
}
//////////////////////////////////////////////////////////////////////
}
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 (ie 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;
}
} | both card addresses need to exist in order to own cards check if it's your own address | function ownerCountOfCard(address owner, address cardAddress) public view returns (uint256) {
require(cardAddressExists(owner));
require(cardAddressExists(cardAddress));
if (owner == cardAddress) {
return 0;
}
uint256 ownerCount = 0;
address[] memory owners = _ownersOf[cardAddress];
for (uint256 i = 0; i < owners.length; i++) {
if (owner == owners[i]) {
ownerCount++;
}
}
return ownerCount;
for (uint256 i = 0; i < owners.length; i++) {
if (owner == owners[i]) {
ownerCount++;
}
}
return ownerCount;
}
| 2,397,822 | [
1,
18237,
5270,
6138,
1608,
358,
1005,
316,
1353,
358,
4953,
18122,
866,
309,
518,
10,
5520,
31,
87,
3433,
4953,
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
] | [
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,
225,
445,
3410,
1380,
951,
6415,
12,
2867,
3410,
16,
1758,
5270,
1887,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
203,
565,
2583,
12,
3327,
1887,
4002,
12,
8443,
10019,
203,
565,
2583,
12,
3327,
1887,
4002,
12,
3327,
1887,
10019,
203,
203,
565,
309,
261,
8443,
422,
5270,
1887,
13,
288,
203,
1377,
327,
374,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
3410,
1380,
273,
374,
31,
203,
565,
1758,
8526,
3778,
25937,
273,
389,
995,
414,
951,
63,
3327,
1887,
15533,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
25937,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
8443,
422,
25937,
63,
77,
5717,
288,
203,
3639,
3410,
1380,
9904,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
327,
3410,
1380,
31,
203,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
25937,
18,
2469,
31,
277,
27245,
288,
203,
1377,
309,
261,
8443,
422,
25937,
63,
77,
5717,
288,
203,
3639,
3410,
1380,
9904,
31,
203,
1377,
289,
203,
565,
289,
203,
203,
565,
327,
3410,
1380,
31,
203,
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
] |
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/contracts/storage/Account.sol | * @dev Returns the total amount of collateral that has been delegated to pools by the account, for the given collateral type./ | function getAssignedCollateral(
Data storage self,
address collateralType
) internal view returns (uint256) {
uint256 totalAssignedD18 = 0;
SetUtil.UintSet storage pools = self.collaterals[collateralType].pools;
for (uint256 i = 1; i <= pools.length(); i++) {
uint128 poolIdx = pools.valueAt(i).to128();
Pool.Data storage pool = Pool.load(poolIdx);
(uint256 collateralAmountD18, ) = pool.currentAccountCollateral(
collateralType,
self.id
);
totalAssignedD18 += collateralAmountD18;
}
return totalAssignedD18;
}
| 16,517,317 | [
1,
1356,
326,
2078,
3844,
434,
4508,
2045,
287,
716,
711,
2118,
30055,
358,
16000,
635,
326,
2236,
16,
364,
326,
864,
4508,
2045,
287,
618,
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,
336,
20363,
13535,
2045,
287,
12,
203,
3639,
1910,
2502,
365,
16,
203,
3639,
1758,
4508,
2045,
287,
559,
203,
565,
262,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
20363,
40,
2643,
273,
374,
31,
203,
203,
3639,
1000,
1304,
18,
5487,
694,
2502,
16000,
273,
365,
18,
12910,
2045,
1031,
63,
12910,
2045,
287,
559,
8009,
27663,
31,
203,
203,
3639,
364,
261,
11890,
5034,
277,
273,
404,
31,
277,
1648,
16000,
18,
2469,
5621,
277,
27245,
288,
203,
5411,
2254,
10392,
2845,
4223,
273,
16000,
18,
1132,
861,
12,
77,
2934,
869,
10392,
5621,
203,
203,
5411,
8828,
18,
751,
2502,
2845,
273,
8828,
18,
945,
12,
6011,
4223,
1769,
203,
203,
5411,
261,
11890,
5034,
4508,
2045,
287,
6275,
40,
2643,
16,
262,
273,
2845,
18,
2972,
3032,
13535,
2045,
287,
12,
203,
7734,
4508,
2045,
287,
559,
16,
203,
7734,
365,
18,
350,
203,
5411,
11272,
203,
5411,
2078,
20363,
40,
2643,
1011,
4508,
2045,
287,
6275,
40,
2643,
31,
203,
3639,
289,
203,
203,
3639,
327,
2078,
20363,
40,
2643,
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
] |
// File: openzeppelin-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.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.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view 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 returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public 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 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 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 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 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 {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @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 {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_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 {
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 Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @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.
*
* 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;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Capped.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
require(cap > 0, "ERC20Capped: cap is 0");
_cap = cap;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol
// 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;
}
// File: contracts/IWETH9.sol
pragma solidity ^0.5.17;
// https://ethereum.stackexchange.com/questions/56466/wrapping-eth-calling-the-weth-contract
contract WETH9_ {
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() external payable ;
function deposit() external payable ;
function withdraw(uint wad) external ;
function totalSupply() external view returns (uint) ;
function approve(address guy, uint wad) external returns (bool) ;
function transfer(address dst, uint wad) external returns (bool) ;
function transferFrom(address src, address dst, uint wad) external returns (bool);
}
// File: contracts/Quado.sol
pragma solidity >=0.5.0;
/**
@title Quado: The Holobots Coin
@dev ERC20 Token to be used as in-world money for the Holobots.world.
* Supports UniSwap to ETH and off-chain deposit/cashout.
* Pre-mints locked funds for liquidity pool bootstrap, developer incentives and infrastructure coverage.
* Approves payout to developers for each 10% of all minted bots, monthly infrastructre costs.
* Bootstrap approved to transfer on creation.
*/
contract Quado is ERC20, ERC20Detailed, ERC20Mintable, ERC20Capped, Ownable, IUniswapV3SwapCallback {
//address god;
uint256 public gasToCashOut = 23731;
uint256 public gasToCashOutToEth = 43731;
uint256 public currentInfrastructureCosts = 200000 * 10**18;
uint256 public percentBootstrap;
uint256 public percentDevteam;
uint256 public percentInfrastructureFund;
uint public lastInfrastructureGrand;
IUniswapV3PoolActions quadoEthUniswapPool;
address payable public quadoEthUniswapPoolAddress;
bool quadoEthUniswapPoolToken0IsQuado;
address public devTeamPayoutAdress;
address public infrastructurePayoutAdress;
uint256 public usedForInfrstructure;
WETH9_ internal WETH;
/**
* @dev Emited when funds for the owner gets approved to be taken from the contract
**/
event OwnerFundsApproval (
uint16 eventType,
uint256 indexed amount
);
/**
* @dev Emited to swap quado cash/quado coin/eth
**/
event SwapEvent (
uint16 eventType,
address indexed owner,
uint256 indexed ethValue,
uint256 indexed coinAmount
);
struct SwapData {
uint8 eventType;
address payable account;
}
/**
* @dev
* @param _maxSupply Max supply of coins
* @param _percentBootstrap How many percent of the currency are reserved for the bootstrap
* @param _percentDevteam How many percent of the currency are reserved for dev incentives
* @param _percentInfrastructureFund How many percent of the currency is reserved to fund infrastcture during game pre-launch
**/
constructor(
uint256 _maxSupply,
uint256 _percentBootstrap,
uint256 _percentDevteam,
uint256 _percentInfrastructureFund,
address _bootstrapPayoutAdress,
address payable _WETHAddr
) public ERC20Detailed("Quado Holobots Coin", "OOOO", 18)
ERC20Capped(_maxSupply)
{
require(_WETHAddr != address(0), "WETH is the zero address");
require(_bootstrapPayoutAdress != address(0), "bootstrap_payout is the zero address");
WETH = WETH9_(_WETHAddr);
// Bootstrap is a stash of coins to provide initial liquidity to the uniswap pool and launch campiagn
percentBootstrap = _percentBootstrap;
// Developer team coverage
percentDevteam = _percentDevteam;
// Funds to cover the expenses for run the infrastructre until launch
percentInfrastructureFund = _percentInfrastructureFund;
usedForInfrstructure = 0;
lastInfrastructureGrand = now;
// Mint the pre-mine
mintOwnerFundsTo((_maxSupply/100)*percentBootstrap, _bootstrapPayoutAdress);
emit OwnerFundsApproval(0, (_maxSupply/100)*percentBootstrap);
}
/**
* @dev ETH to Quado Cash
*/
function toQuadoCash(uint160 sqrtPriceLimitX96) public payable {
wrap(msg.value);
WETH.approve(quadoEthUniswapPoolAddress, msg.value);
// → coinswap ETH/OOOO
// docs: https://docs.uniswap.org/reference/core/interfaces/pool/IUniswapV3PoolActions
/*
swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes data) external returns (int256 amount0, int256 amount1)
*/
quadoEthUniswapPool.swap(address(this), !quadoEthUniswapPoolToken0IsQuado, int256(msg.value), sqrtPriceLimitX96, swapDataToBytes(SwapData(2, msg.sender)));
}
/**
* @dev ETH to Quado Coin
*/
function toQuadoCoin(uint160 sqrtPriceLimitX96) public payable {
wrap(msg.value);
WETH.approve(quadoEthUniswapPoolAddress, msg.value);
// → coinswap ETH/OOOO
quadoEthUniswapPool.swap(address(this), !quadoEthUniswapPoolToken0IsQuado, int256(msg.value), sqrtPriceLimitX96, swapDataToBytes(SwapData(4, msg.sender)));
}
/**
* @dev Quado Coin to ETH
* @param _amount amount of quado to swap to eth
*/
function toETH(uint256 _amount, uint160 sqrtPriceLimitX96) public {
require(_amount <= balanceOf(msg.sender), 'low_balance');
_approve(msg.sender, quadoEthUniswapPoolAddress, _amount);
// → coinswap OOOO/ETH
quadoEthUniswapPool.swap(address(this), quadoEthUniswapPoolToken0IsQuado, int256(_amount), sqrtPriceLimitX96, swapDataToBytes(SwapData(3, msg.sender)));
}
function wrap(uint256 ETHAmount) private
{
//create WETH from ETH
if (ETHAmount != 0) {
WETH.deposit.value(ETHAmount)();
}
require(WETH.balanceOf(address(this)) >= ETHAmount, "eth_not_deposited");
}
function unwrap(uint256 Amount) private
{
if (Amount != 0) {
WETH.withdraw(Amount);
}
}
// default method when ether is paid to the contract's address
// used for the WETH withdraw callback
function() external payable {
}
function bytesToAddress(bytes memory bys) private pure returns (address payable addr) {
assembly {
addr := div( mload( add(bys, 32) ), 0x1000000000000000000000000)
}
}
// https://ethereum.stackexchange.com/questions/11246/convert-struct-to-bytes-in-solidity
function swapDataFromBytes(bytes memory data) private pure returns (SwapData memory d) {
d.eventType = uint8(data[20]);
bytes memory adr20 = new bytes(20);
for (uint i=0;i<20;i++) {
adr20[i]=data[i];
}
d.account = bytesToAddress(adr20);
}
function swapDataToBytes(SwapData memory swapData) private pure returns (bytes memory data) {
uint _size = 1 + 20;
bytes memory _data = new bytes(_size);
_data[20] = byte(swapData.eventType);
uint counter=0;
bytes20 adr = bytes20(address(swapData.account));
for (uint i=0;i<20;i++) {
_data[counter]=adr[i];
counter++;
}
return (_data);
}
/**
* @dev Uniswap swap callback, satisfy IUniswapV3SwapCallback
* https://docs.uniswap.org/reference/core/interfaces/callback/IUniswapV3SwapCallback
*/
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
require(msg.sender == quadoEthUniswapPoolAddress, 'uni_sender');
SwapData memory swapData = swapDataFromBytes(data);
require(swapData.eventType > 0, 'swap_data_type');
require((amount0Delta > 0) || (amount1Delta > 0), 'delta_pos');
int256 quadoAmount = quadoEthUniswapPoolToken0IsQuado ? amount0Delta : amount1Delta;
int256 ethAmount = quadoEthUniswapPoolToken0IsQuado ? amount1Delta : amount0Delta;
if(quadoAmount > 0) {
// OOOO is needed by the pool, means quado to ETH
require(uint256(quadoAmount) <= balanceOf(swapData.account), 'owner_oooo_bal');
transferFrom(swapData.account, msg.sender, uint256(quadoAmount));
// pay the owner the ETH he got
// UNWRAP WETH
// https://ethereum.stackexchange.com/questions/83929/while-testing-wrap-unwrap-of-eth-to-weth-on-kovan-however-the-wrap-function-i
unwrap(uint256(-ethAmount));
swapData.account.transfer( uint256(-ethAmount)); //, 'eth_to_acc');
emit SwapEvent(3, swapData.account, uint256(ethAmount), uint256(quadoAmount));
} else if(ethAmount > 0) {
// ETH is needed, means eth to quado cash (eventType 2) or coin (eventType 4)
//require(uint256(amount0Delta) <= address(this).balance, 'contract_eth_bal');
require(WETH.balanceOf(address(this)) >= uint256(ethAmount), 'contract_weth_bal');
// Transfer WRAPPED ETH to contract
WETH.transfer(quadoEthUniswapPoolAddress, uint256(ethAmount));
//quadoEthUniswapPoolAddress.transfer(uint256(amount0Delta));// ), 'eth_to_uni');
// pay the owner the OOOO he got
if(swapData.eventType == 2) {
// inform the cash system that it should mint coins to the owner
emit SwapEvent(2, swapData.account, uint256(ethAmount), uint256(-quadoAmount));
} else {
emit SwapEvent(4, swapData.account, uint256(ethAmount), uint256(-quadoAmount));
_approve(address(this), quadoEthUniswapPoolAddress, uint256(-quadoAmount));
transferFrom(address(this), swapData.account, uint256(-quadoAmount));
}
}
}
/**
* @dev Quado Cash to Coin: Emits event to cash out deposited Quado Cash to Quado in user's wallet
* @param _amount amount of quado cash to cash out
*/
function cashOut(uint256 _amount, bool _toEth) public payable {
require(msg.value >= tx.gasprice * (_toEth ? gasToCashOutToEth : gasToCashOut), "min_gas_to_cashout");
// pay owner the gas fee it needs to call settlecashout
address payable payowner = address(uint160(owner()));
require(payowner.send( msg.value ), "fees_to_owner");
//→ emit event
emit SwapEvent(_toEth ? 7 : 1, msg.sender, msg.value, _amount);
}
/**
* @dev Cashes out deposited Quado Cash to Quado in user's wallet
* @param _to address of the future owner of the token
* @param _amount how much Quado to cash out
* @param _notMinted not minted cash to reflect on blockchain
*/
function settleCashOut(address payable _to, uint256 _amount, bool _toEth, uint160 sqrtPriceLimitX96, uint256 _notMinted) public onlyOwner {
mintFromCash(_notMinted);
// must be done in any case, so it can be taken from him for uniswap or left if not swapped
transferFrom(address(this), _to, _amount);
if(_toEth) {
// owner wanted ETH in return to Cash
//require(_amount <= balanceOf(_to), 'low_balance');
_approve(_to, quadoEthUniswapPoolAddress, _amount);
quadoEthUniswapPool.swap(
address(this),
quadoEthUniswapPoolToken0IsQuado,
int256(_amount),
sqrtPriceLimitX96,
swapDataToBytes(SwapData(3, _to))
);
}
}
/**
* @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 returns (bool) {
_transfer(msg.sender, recipient, amount);
// if it's a cash deposit transfer
if(recipient == address(this)) {
_approve(address(this), owner(), amount);
// signal the cash system the deposit
emit SwapEvent(5, msg.sender, 0, amount);
}
return true;
}
/**
* @dev Mints token to one of the payout adddresses for bootstrap, infrastructure and dev team
* @dev Approves the contract owner to transfer that minted tokens
* @param _amount mints this amount of Quado to the contract itself
* @param _to address on where to mint
*/
function mintOwnerFundsTo(uint256 _amount, address _to) internal onlyMinter {
require(_amount > 0, "zero amount to mint");
require(_to != address(0), "mint to is zero address");
//_approve(address(this), msg.sender, _amount);
//_transfer(address(this), _to, _amount);
mint(_to, _amount);
_approve(_to, owner(), _amount);
}
/**
* @dev Reflects the current quado cash state to quado coin by minting to the contract itself
* @dev Approves the contract owner to transfer that minted cash later
* @dev Additionally approves pre-minted funds for hardware payment and dev incentives
* @param _amount mints this amount of Quado to the contract itself
*/
function mintFromCash(uint256 _amount) public onlyMinter {
uint256 totalApprove = _amount;
if(_amount > 0) {
mint(address(this), _amount);
// approve for later cashout
_approve(address(this), owner(), totalApprove);
// check if a 10% milestone is broken, and if so grant the dev team 10% of their fund
if( (totalSupply() * 10 / cap()) < ((totalSupply() + _amount) * 10 / cap()) ) {
uint256 devFunds = cap()/100*percentDevteam/10;
mintOwnerFundsTo(devFunds, devTeamPayoutAdress);
emit OwnerFundsApproval(2, devFunds);
}
}
// check for next infrastructure cost settlement
if ((now >= lastInfrastructureGrand + 4 * 1 weeks)
&& ((usedForInfrstructure + currentInfrastructureCosts) <= (cap()/100 * percentInfrastructureFund))
) {
usedForInfrstructure += currentInfrastructureCosts;
lastInfrastructureGrand = now;
mintOwnerFundsTo(currentInfrastructureCosts, infrastructurePayoutAdress);
emit OwnerFundsApproval(1, currentInfrastructureCosts);
}
}
function setGasToCashOutEstimate(uint256 _cashOut, uint256 _cashOutToEth) public onlyOwner {
gasToCashOut = _cashOut;
gasToCashOutToEth = _cashOutToEth;
}
function setCurrentInfrastructureCosts(uint256 _costs) public onlyOwner {
currentInfrastructureCosts = _costs;
}
function setUniswapPool(address payable _poolAddress) public onlyOwner {
IUniswapV3PoolImmutables poolImmu = IUniswapV3PoolImmutables(_poolAddress);
require((poolImmu.token0() == address(this)) || (poolImmu.token1() == address(this)));
quadoEthUniswapPoolToken0IsQuado = (poolImmu.token0() == address(this));
quadoEthUniswapPoolAddress = _poolAddress;
quadoEthUniswapPool = IUniswapV3PoolActions(quadoEthUniswapPoolAddress);
}
function setPayoutAddresses(address _devTeamPayoutAdress, address _infrastructurePayoutAdress) public onlyOwner {
devTeamPayoutAdress = _devTeamPayoutAdress;
infrastructurePayoutAdress = _infrastructurePayoutAdress;
}
/**
* @dev Withdraw ether from this contract (Callable by owner)
*/
function withdrawETH(uint256 amount) public onlyOwner {
require(amount <= address(this).balance, 'balance_low');
require(msg.sender.send(amount), 'no_send');
}
/*function setGod(address _god) public onlyOwner {
god = _god;
}*/
} | @title Permissionless pool actions @notice Contains pool methods that can be called by anyone | interface IUniswapV3PoolActions {
function initialize(uint160 sqrtPriceX96) external;
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
pragma solidity >=0.5.0;
}
| 369,643 | [
1,
5041,
2656,
2845,
4209,
225,
8398,
2845,
2590,
716,
848,
506,
2566,
635,
1281,
476,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5831,
467,
984,
291,
91,
438,
58,
23,
2864,
6100,
288,
203,
565,
445,
4046,
12,
11890,
16874,
5700,
5147,
60,
10525,
13,
3903,
31,
203,
203,
565,
445,
312,
474,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
1769,
203,
203,
565,
445,
3274,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
20,
11244,
16,
203,
3639,
2254,
10392,
3844,
21,
11244,
203,
565,
262,
3903,
1135,
261,
11890,
10392,
3844,
20,
16,
2254,
10392,
3844,
21,
1769,
203,
203,
565,
445,
18305,
12,
203,
3639,
509,
3247,
4024,
4070,
16,
203,
3639,
509,
3247,
4024,
5988,
16,
203,
3639,
2254,
10392,
3844,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
20,
16,
2254,
5034,
3844,
21,
1769,
203,
203,
565,
445,
7720,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
1426,
3634,
1290,
3335,
16,
203,
3639,
509,
5034,
3844,
17068,
16,
203,
3639,
2254,
16874,
5700,
5147,
3039,
60,
10525,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
1135,
261,
474,
5034,
3844,
20,
16,
509,
5034,
3844,
21,
1769,
203,
203,
565,
445,
9563,
12,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
20,
16,
203,
3639,
2254,
2
] |
./full_match/1/0x94b4fb16893C0Fb4E470eEf2559C24FD87FEd5F1/sources/src/Propdates.sol | @notice Accepts the pending prop update admin power @param propId The id of the prop | function acceptPropUpdateAdmin(uint256 propId) external {
if (msg.sender != pendingPropUpdateAdmin[propId]) {
revert OnlyPendingPropUpdateAdmin();
}
_acceptPropUpdateAdmin(propId);
}
| 17,007,589 | [
1,
26391,
326,
4634,
2270,
1089,
3981,
7212,
225,
2270,
548,
1021,
612,
434,
326,
2270,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2791,
4658,
1891,
4446,
12,
11890,
5034,
2270,
548,
13,
3903,
288,
203,
3639,
309,
261,
3576,
18,
15330,
480,
4634,
4658,
1891,
4446,
63,
5986,
548,
5717,
288,
203,
5411,
15226,
5098,
8579,
4658,
1891,
4446,
5621,
203,
3639,
289,
203,
203,
3639,
389,
9436,
4658,
1891,
4446,
12,
5986,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
// DataHashAuth implements contract for registering authentic
// products hash inside the ledger by hashing their unique attributes
// and validating products authenticity providing the same set of attributes.
contract DataHashAuth {
// TProduct defines the scanned product information stored inside
// the contract for future validation.
struct TProduct {
string name; // name of the product
string producerName; // name of the product manufacturer
string batchNo; // production batch number
string barcodeNo; // barcode of the product
uint64 productionDate; // the UTC timestamp of the production date
uint64 expiryDate; // the UTC timestamp of the expiration date
uint64 added; // the time stamp of the product record creation
uint64 updated; // the time stamp of the last product update
uint64 invalidated; // the time stamp of the product invalidation
bytes32 productHash; // hash of the product data for validation
}
// InputProduct defines a structure for product input.
struct InputProduct {
uint64 pid; // unique product identifier
string name; // name of the product
string producer; // name of the producer
string batchNo; // batch number
string barcodeNo; // barcode number
uint64 productionDate; // timestamp of the production
uint64 expiryDate; // timestamp of the expiration
}
// admin is the account allowed to change contract parameters.
address public _admin;
// proManagers are the accounts allowed to add new products
// and product related data into the contract.
mapping (address => bool) public _proManagers;
// products represents mapping between unique product PID
// and the product details record held inside the contract.
mapping(uint64 => TProduct) public _products;
// pinToProductPid represents mapping between authentic product PIN
// and a unique product identifier, the PID.
mapping(uint256 => uint64) public _pinToProductPid;
// ProductAdded event is emitted on new product receival.
event ProductAdded(uint64 indexed _pid, bytes32 _hash, uint64 _timestamp);
// ProductUpdated event is emitted on an existing product data change.
event ProductUpdated(uint64 indexed _pid, bytes32 _hash, uint64 _timestamp);
// ProductInvalidated event is emitted on marking a product as invalid.
event ProductInvalidated(uint64 indexed _pid, uint64 _timestamp);
// PinAdded event is emitted on adding a new PIN to the contract.
event PinAdded(uint64 indexed _pid, uint256 indexed _pin, uint64 _timestamp);
// ManagerPromoted event is emitted on adding new authorized scanner.
event ManagerPromoted(address indexed _addr, uint64 _timestamp);
// ManagerDemoted event is emitted on removing a scanner from authorized.
event ManagerDemoted(address indexed _addr, uint64 _timestamp);
// constructor initializes new contract instance on deployment
// the creator will also become the hash repository manager
constructor() public payable {
// keep the administrator reference
_admin = msg.sender;
// administrator is the first one allowed to manage products
_proManagers[msg.sender] = true;
}
// ----------------------------------------------------------------
// products management
// ----------------------------------------------------------------
// setProduct adds or updates a product information
// from an authorized product manager address in the contract.
function setProduct(InputProduct calldata _product) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// the product PIN is expected to be unique
bool isNew = (_products[_product.pid].added == 0);
// calculate the hash
bytes32 _hash = _hashProduct(
_product.pid,
_product.name,
_product.producer,
_product.batchNo,
_product.barcodeNo,
_product.expiryDate,
_product.productionDate);
// enlist the product in the contract (aloc the storage for it)
TProduct storage inProduct = _products[_product.pid];
// update the product data
inProduct.name = _product.name;
inProduct.producerName = _product.producer;
inProduct.batchNo = _product.batchNo;
inProduct.barcodeNo = _product.barcodeNo;
inProduct.productionDate = _product.productionDate;
inProduct.expiryDate = _product.expiryDate;
inProduct.productHash = _hash;
// set the product timestamp record to recognize the action
// and emit the appropriate product event
if (isNew) {
// the product didn't exist before and so it's a new one
inProduct.added = uint64(now);
emit ProductAdded(_product.pid, _hash, uint64(now));
} else {
// the product existed before and so it's an update
inProduct.updated = uint64(now);
emit ProductUpdated(_product.pid, _hash, uint64(now));
}
}
// invalidate a product identified by it's unique PID id.
function invalidate(uint64 _pid) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// make sure the product is known
require(_products[_pid].added > 0, "unknown product");
// make the change
_products[_pid].invalidated = uint64(now);
// emit the event
emit ProductInvalidated(_pid, uint64(now));
}
// _hash calculates the hash of the product used for both
// the product registration and validation procedures.
function _hashProduct(
uint64 _pid,
string memory _name,
string memory _producerName,
string memory _batchNo,
string memory _barcodeNo,
uint64 _productionDate,
uint64 _expiryDate
) internal pure returns (bytes32) {
// calculate the hash from encoded product data pack
return keccak256(abi.encode(
_pid,
_name,
_batchNo,
_barcodeNo,
_expiryDate,
_productionDate,
_producerName
));
}
// ----------------------------------------------------------------
// product PIN management (the PIN is what's printed on QR patches)
// ----------------------------------------------------------------
// addPins adds a new set of PINs for the product identified
// by the unique product PID.
function addPins(uint64 _pid, uint256[] calldata _pins) external {
// make sure this is autenticated access
require(_proManagers[msg.sender], "access restricted");
// we do not check product existence here since the product may
// be added later based on client data processing queue.
for (uint i = 0; i < _pins.length; i++) {
// make sure this pin is new
if (0 == _pinToProductPid[_pins[i]]) {
// add the PIN to PID link
_pinToProductPid[_pins[i]] = _pid;
// emit the event
emit PinAdded(_pid, _pins[i], uint64(now));
}
}
}
// ckeck validates product authenticity for the given product data set
// using an internal authentic products list. Anybody can authenticate
// products using this function, no access restrictions are applied.
function check(
uint256 _pin,
string memory _name,
string memory _producerName,
string memory _batchNo,
string memory _barcodeNo,
uint64 _productionDate,
uint64 _expiryDate
) public view returns (bool) {
// do we even know the PIN?
if (0 == _pinToProductPid[_pin]) {
return false;
}
// get the product PID
uint64 _pid = _pinToProductPid[_pin];
// calculate the hash
bytes32 _hash = _hashProduct(
_pid,
_name,
_producerName,
_batchNo,
_barcodeNo,
_expiryDate,
_productionDate);
// compare the product details hash with the stored product details
// make sure the product has not been invalidated
return (
_hash == _products[_pid].productHash &&
0 == _products[_pid].invalidated
);
}
// ----------------------------------------------------------------
// contract internals management
// ----------------------------------------------------------------
// promote adds a new authorized scanner address
// into the contract.
function promote(address _addr) external {
// only manager can authorize
require(msg.sender == _admin, "access restricted");
// authorize the address and inform listeners
_proManagers[_addr] = true;
emit ManagerPromoted(_addr, uint64(now));
}
// demote removes the specified address
// from authorized scanners.
function demote(address _addr) external {
// only manager can authorize
require(msg.sender == _admin, "access restricted");
// authorize the address
_proManagers[_addr] = false;
emit ManagerDemoted(_addr, uint64(now));
}
}
| products represents mapping between unique product PID and the product details record held inside the contract. | mapping(uint64 => TProduct) public _products;
| 2,550,582 | [
1,
18736,
8686,
2874,
3086,
3089,
3017,
14788,
471,
326,
3017,
3189,
1409,
15770,
4832,
326,
6835,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
12,
11890,
1105,
516,
399,
4133,
13,
1071,
389,
18736,
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
] |
pragma solidity ^0.4.24;
/*
* The Option Underwriting Engine on Ethereum
* In this version, a owner can have only one bid/ask or option contracts
* Author: Jinhua Wang
* Apache License
* Version 2.0, January 2004
* http://www.apache.org/licenses/
*/
import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; //import the oraclize api
import "https://github.com/ginward/openzeppelin-solidity/contracts/math/SafeMath.sol"; //import the safe math library
import "https://github.com/ginward/openzeppelin-solidity/contracts/math/SafeMath64.sol"; //import the safe math library
import "https://github.com/ginward/rbt-solidity/contracts/RedBlackTree.sol"; //import the red black tree
contract exchange is usingOraclize{
using SafeMath for uint;
using SafeMath64 for uint64;
mapping (address => uint) balance; //the balance account for all traders
mapping (address => uint) marginBalance; //the balance of margin account. frozen unless canceled order
uint constant contract_size = 100; //the number of stocks underlying the contract. Uint is 1 cent USD. 100 cents = 1USD
uint constant maturity_date = 20180701; //the maturity date should be in YYYYMMDD
uint constant strike = 200; //the strike price of the option contract, in USD
string constant ticker = "AAPL"; //the apple ticker
uint64 nodeid_bid=1; //the unique node id which maps to node that contains the order information for bid
uint64 nodeid_ask=1; //the unique node id which maps to node that contains the order information for ask
mapping (address => uint64) bidorders; //map each owner to a tree node
mapping (address => uint64) askorders;
mapping (uint64 => bid[]) bidnodes; //map each tree node to bid orders
mapping (uint64 => ask[]) asknodes; //map each tree node to ask orders
mapping (address => bytes32) optionOwners; //map to the options. one owner can have only one option.
mapping (bytes32 => option) options; //option details
struct bid {
//the bid object
uint price;
uint volume;
uint timestamp;
address owner;
}
struct ask {
//the ask object
uint margin; //when the trader asks, he needs to provide a margin
uint price;
uint volume;
uint timestamp;
address owner;
}
struct option {
address long;
address short;
uint volume;
uint margin;
uint timestamp;
}
//the red black tree structures
using RedBlackTree for RedBlackTree.Tree;
RedBlackTree.Tree AskOrderBook;
RedBlackTree.Tree BidOrderBook;
function placeBid() public payable{
/*
* Function to place bid order
* One address can only place one bid
*/
//first check if the sender already has an order. if so, he is not allowed to send another one until this one gets executed
//expect to upgrade to multiple orders in version 2.0
if (bidorders[msg.sender]!=0||askorders[msg.sender]!=0||optionOwners[msg.sender]!=0){
revert();
}
uint p=msg.value;
//add the money to balance
balance[msg.sender].add(p);
bid memory bidObj;
bidObj.price=p;
bidObj.timestamp=now;
bidObj.owner=msg.sender;
nodeid_bid=nodeid_bid.add(1);
bidorders[msg.sender]=nodeid_bid;
BidOrderBook.insert(nodeid_bid,p);
bidnodes[nodeid_bid].push(bidObj);
}
function placeAsk(uint p) public payable{
/*
* Function to place ask order
* One address can only place one ask
*/
//check if the sender already has an order
if(bidorders[msg.sender]!=0||askorders[msg.sender]!=0||optionOwners[msg.sender]!=0){
revert();
}
uint m=msg.value; //the money sent alone is the margin
marginBalance[msg.sender].add(m);
ask memory askObj;
askObj.margin=m;
askObj.price=p; //the ask price is passed in as a parameter
askObj.timestamp=now;
askObj.owner=msg.sender;
nodeid_ask=nodeid_ask.add(1);
askorders[msg.sender]=nodeid_ask;
AskOrderBook.insert(nodeid_ask,p);
asknodes[nodeid_ask].push(askObj);
}
function matchOrders() private {
/*
* Function to match the orders in the orderbook
*/
uint64 maxbid_id=BidOrderBook.getMaximum();
if (maxbid_id==0){
revert();
}
RedBlackTree.Item memory maxbid_item=BidOrderBook.items[maxbid_id];
uint maxprice=maxbid_item.value;
uint64 minask_id=AskOrderBook.getMinimum();
if(minask_id==0){
revert();
}
RedBlackTree.Item memory minask_item=AskOrderBook.items[minask_id];
uint minprice=minask_item.value;
//check if the orderbook crosses
if (minprice<maxprice){
bid[] bidArr=bidnodes[maxbid_id];
ask[] askArr=asknodes[minask_id];
if (bidArr.length==0){
BidOrderBook.remove(maxbid_id);
//could have been a recursive call to matchOrders. but considering it is not a good practice and could burn the money,
//did't implement it
revert();
}
if (askArr.length==0){
AskOrderBook.remove(minask_id);
revert();
}
bid bid_order=bidArr[0];
ask ask_order=askArr[0];
//the orderbook crosses, execute the orders
option memory opt;
opt.long=bid_order.owner;
opt.short=ask_order.owner;
//check if the option owners still have orders outstanding
if(optionOwners[opt.long].length!=0){
//delete the bid
delete bidArr[0];
revert();
}
if(optionOwners[opt.short].length!=0){
//delete the ask
delete askArr[0];
revert();
}
//the bid volume
uint vol_bid=bid_order.volume;
//the ask volume
uint vol_ask=ask_order.volume;
if(vol_bid==vol_ask) {
//when bid volume is equal to ask volume
opt.volume=vol_ask;
opt.margin=ask_order.margin;
opt.timestamp=now;
//if the bid or ask array is empty, should delete the array
if (bidArr.length==0) {
delete bidnodes[maxbid_id];
//delete the element in the mapping
delete bidorders[bid_order.owner];
//delete the element in the tree
BidOrderBook.remove(maxbid_id);
} else {
//clear the outstanding bid order
delete bidArr[0];
}
if (askArr.length==0){
delete asknodes[minask_id];
delete askorders[ask_order.owner];
AskOrderBook.remove(minask_id);
} else {
//clean the outstanding ask order
delete askArr[0];
}
}
else if (vol_bid>vol_ask){
//bid volume > ask volume
opt.volume=vol_ask;
opt.margin=ask_order.margin;
opt.timestamp=now;
//keep part of the bid order outstanding
bidArr[0].volume=bidArr[0].volume.sub(vol_ask);
//clear the entire array if the ask array is 0
if (askArr.length==0){
delete asknodes[minask_id];
delete askorders[ask_order.owner];
AskOrderBook.remove(minask_id);
} else {
//clear the outstanding ask order
delete askArr[0];
}
}
else{
//ask volume > bid volume
opt.volume=vol_bid;
opt.margin=ask_order.margin;
opt.timestamp=now;
//keep part of the ask order outstanding
askArr[0].volume=askArr[0].volume.sub(vol_bid);
if (bidArr.length==0){
delete bidnodes[maxbid_id];
//delete the element in the mapping
delete bidorders[bid_order.owner];
//delete the element in the tree
BidOrderBook.remove(maxbid_id);
} else {
//clear the outstanding bid order
delete bidArr[0];
}
}
bytes32 hashOpt;
//hash the option contract and push it into the map of all options
hashOpt=keccak256(opt.long, opt.short, opt.volume, opt.margin, opt.timestamp);
options[hashOpt]=opt;
//keep track of who owns the option
optionOwners[opt.long]=hashOpt;
optionOwners[opt.short]=hashOpt;
}
}
function cancelBid() public{
//the node id
uint64 id=bidorders[msg.sender];
bid[] bidArr=bidnodes[id];
//delete from orderbook
for (uint i=0;i<bidArr.length;i++){
bid bid_order=bidArr[i];
if (bid_order.owner==msg.sender){
delete bidArr[i];
}
}
if (bidnodes[id].length==0){
BidOrderBook.remove(id);
}
bidorders[msg.sender]=0;//reset the bidorders
}
function cancelAsk() public{
uint marginOrder=0;
//the node id
uint64 id=askorders[msg.sender];
ask []askArr=asknodes[id];
//delete from orderbook
for (uint i=0;i<askArr.length;i++){
ask ask_order=askArr[i];
if (ask_order.owner==msg.sender){
marginOrder=ask_order.margin;
delete askArr[i];
}
}
//recover the margin value
marginBalance[msg.sender].sub(marginOrder);
balance[msg.sender].add(marginOrder);
delete asknodes[id]; //delete from orderbook
if(asknodes[id].length==0){
AskOrderBook.remove(id);
}
askorders[msg.sender]=0;
}
function mature() public{
//this function is called when the contract matures
}
} | the balance account for all traders
| mapping (address => uint) balance; | 6,367,104 | [
1,
5787,
11013,
2236,
364,
777,
1284,
6794,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
202,
6770,
261,
2867,
516,
2254,
13,
11013,
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
] |
./partial_match/100/0xc9d000B8DECde065336Ad7A1e1EFDB3067E277b7/sources/DMEX_Trading.sol | currentBlock / fundingInterval - entryBlock / fundingInterval | {
uint256 fundingRate = futuresContracts[futuresContractHash].fundingRate;
uint256 multiplier = futuresContracts[futuresContractHash].multiplier;
uint256 fundingCost = safeMul(safeMul(safeMul(safeMul(safeSub(block.number/fundingInterval, entryBlock/fundingInterval), fundingInterval), fundingRate), safeMul(qty, price)/1e8)/1e18, multiplier)/1e8;
return fundingCost;
}
| 16,659,017 | [
1,
2972,
1768,
342,
22058,
4006,
300,
1241,
1768,
342,
22058,
4006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
288,
203,
3639,
2254,
5034,
22058,
4727,
273,
15583,
20723,
63,
74,
10945,
8924,
2310,
8009,
74,
14351,
4727,
31,
203,
3639,
2254,
5034,
15027,
273,
15583,
20723,
63,
74,
10945,
8924,
2310,
8009,
20538,
31,
203,
203,
203,
3639,
2254,
5034,
22058,
8018,
273,
4183,
27860,
12,
4626,
27860,
12,
4626,
27860,
12,
4626,
27860,
12,
4626,
1676,
12,
2629,
18,
2696,
19,
74,
14351,
4006,
16,
1241,
1768,
19,
74,
14351,
4006,
3631,
22058,
4006,
3631,
22058,
4727,
3631,
4183,
27860,
12,
85,
4098,
16,
6205,
13176,
21,
73,
28,
13176,
21,
73,
2643,
16,
15027,
13176,
21,
73,
28,
31,
203,
203,
3639,
327,
22058,
8018,
31,
21281,
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
] |
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// @openzeppelin/[email protected]
interface IMigratorChef {
function migrate(IERC20 token) external returns (IERC20);
}
// Generator is the Miner of AF. He can make AF 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 AF is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract Generator is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accAFPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accAFPerShare` (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. AFs to distribute per block.
uint256 lastRewardBlock; // Last block number that AFs distribution occurs.
uint256 accAFPerShare; // Accumulated AFs per share, times 1e12. See below.
}
// The AF TOKEN!
IERC20 public tokenAF;
// total mint amount.
uint256 public mintReward;
uint public constant SUSPEND_MINING_BALANCE = 100000e8;
// Dev address.
address public devaddr;
// Block number when bonus AF period ends.
uint256 public bonusEndBlock;
// AF tokens created per block.
uint256 public tokenAFPerBlock;
// Bonus muliplier for early AF makers.
uint256 public constant BONUS_MULTIPLIER = 5;
// 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 AF mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Mint(address indexed to, uint256 amount);
constructor(
IERC20 _tokenAF,
address _devaddr,
uint256 _tokenAFPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
tokenAF = _tokenAF;
devaddr = _devaddr;
tokenAFPerBlock = _tokenAFPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAFPerShare: 0
}));
}
// Update the given pool's AF allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// 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;
}
// Migrate AF token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrateAF() public {
require(address(migrator) != address(0), "migrate: no migrator token");
uint256 bal = tokenAF.balanceOf(address(this));
tokenAF.safeApprove(address(migrator), bal);
IERC20 newToken = migrator.migrate(tokenAF);
require(bal == newToken.balanceOf(address(this)), "migrate: bad");
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) {
return 0;
}
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 AFs on frontend.
function pendingAF(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAFPerShare = pool.accAFPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAFPerShare = accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAFPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
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 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, tokenAFReward.div(10));
mintReward.add(tokenAFReward);
pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to Generator for AF rewards.
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.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from Generator.
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.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe AF transfer function, just in case if rounding error causes pool to not have enough AFs.
function safeAFTransfer(address _to, uint256 _amount) internal {
uint256 AFBal = tokenAF.balanceOf(address(this));
if (_amount > AFBal) {
tokenAF.transfer(_to, AFBal);
} else {
tokenAF.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function mint(address to, uint256 rewardAmount) private {
if (rewardAmount == 0) {
emit Mint(to, 0);
return;
}
require(tokenAF.transfer(to, rewardAmount),
'Generator: transfer out of unlocked pool failed');
emit Mint(to, rewardAmount);
}
}
| Generator is the Miner of AF. He can make AF 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 AF is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract Generator is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
}
struct PoolInfo {
}
uint public constant SUSPEND_MINING_BALANCE = 100000e8;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Mint(address indexed to, uint256 amount);
constructor(
IERC20 _tokenAF,
address _devaddr,
uint256 _tokenAFPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
IERC20 public tokenAF;
uint256 public mintReward;
address public devaddr;
uint256 public bonusEndBlock;
uint256 public tokenAFPerBlock;
uint256 public constant BONUS_MULTIPLIER = 5;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
) public {
tokenAF = _tokenAF;
devaddr = _devaddr;
tokenAFPerBlock = _tokenAFPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAFPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAFPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accAFPerShare: 0
}));
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
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;
}
function migrateAF() public {
require(address(migrator) != address(0), "migrate: no migrator token");
uint256 bal = tokenAF.balanceOf(address(this));
tokenAF.safeApprove(address(migrator), bal);
IERC20 newToken = migrator.migrate(tokenAF);
require(bal == newToken.balanceOf(address(this)), "migrate: bad");
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) {
return 0;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) {
return 0;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (tokenAF.balanceOf(address(this)) < SUSPEND_MINING_BALANCE) {
return 0;
}
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
} else if (_from >= bonusEndBlock) {
} else {
function pendingAF(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAFPerShare = pool.accAFPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAFPerShare = accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAFPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingAF(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accAFPerShare = pool.accAFPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accAFPerShare = accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accAFPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, tokenAFReward.div(10));
mintReward.add(tokenAFReward);
pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, tokenAFReward.div(10));
mintReward.add(tokenAFReward);
pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 tokenAFReward = multiplier.mul(tokenAFPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
mint(devaddr, tokenAFReward.div(10));
mintReward.add(tokenAFReward);
pool.accAFPerShare = pool.accAFPerShare.add(tokenAFReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accAFPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeAFTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accAFPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeAFTransfer(address _to, uint256 _amount) internal {
uint256 AFBal = tokenAF.balanceOf(address(this));
if (_amount > AFBal) {
tokenAF.transfer(_to, AFBal);
tokenAF.transfer(_to, _amount);
}
}
function safeAFTransfer(address _to, uint256 _amount) internal {
uint256 AFBal = tokenAF.balanceOf(address(this));
if (_amount > AFBal) {
tokenAF.transfer(_to, AFBal);
tokenAF.transfer(_to, _amount);
}
}
} else {
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function mint(address to, uint256 rewardAmount) private {
if (rewardAmount == 0) {
emit Mint(to, 0);
return;
}
require(tokenAF.transfer(to, rewardAmount),
'Generator: transfer out of unlocked pool failed');
emit Mint(to, rewardAmount);
}
function mint(address to, uint256 rewardAmount) private {
if (rewardAmount == 0) {
emit Mint(to, 0);
return;
}
require(tokenAF.transfer(to, rewardAmount),
'Generator: transfer out of unlocked pool failed');
emit Mint(to, rewardAmount);
}
}
| 5,438,302 | [
1,
3908,
353,
326,
5444,
264,
434,
10888,
18,
8264,
848,
1221,
10888,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
10888,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
16351,
10159,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
565,
2254,
1071,
5381,
11726,
3118,
4415,
67,
6236,
1360,
67,
38,
1013,
4722,
273,
25259,
73,
28,
31,
203,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
490,
474,
12,
2867,
8808,
358,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
467,
654,
39,
3462,
389,
2316,
6799,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
3639,
2254,
5034,
389,
2316,
6799,
2173,
1768,
16,
203,
3639,
2254,
5034,
389,
1937,
1768,
16,
203,
3639,
2254,
5034,
389,
18688,
407,
1638,
1768,
203,
565,
467,
654,
39,
3462,
1071,
1147,
6799,
31,
203,
565,
2254,
5034,
1071,
312,
474,
17631,
1060,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
324,
22889,
1638,
1768,
31,
203,
565,
2254,
5034,
1071,
1147,
6799,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
2
] |