comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
// Frees up to `value` sub-tokens owned by address `from`. Returns how many tokens were freed.
// Otherwise, identical to `freeFrom`.
|
function freeFromUpTo(address from, uint256 value) public returns (uint256 freed) {
address spender = msg.sender;
uint256 from_balance = s_balances[from];
if (value > from_balance) {
value = from_balance;
}
mapping(address => uint256) from_allowances = s_allowances[from];
uint256 spender_allowance = from_allowances[spender];
if (value > spender_allowance) {
value = spender_allowance;
}
freeStorage(value);
s_balances[from] = from_balance - value;
from_allowances[spender] = spender_allowance - value;
return value;
}
|
0.4.20
|
/// @notice Creates a vesting position
/// @param account Account which to add vesting position for
/// @param startTime when the positon should start
/// @param amount Amount to add to vesting position
/// @dev The startstime paramter allows some leeway when creating
/// positions for new employees
|
function vest(address account, uint256 startTime, uint256 amount) external override onlyOwner {
require(account != address(0), "vest: !account");
require(amount > 0, "vest: !amount");
if (startTime + START_TIME_LOWER_BOUND < block.timestamp) {
startTime = block.timestamp;
}
EmployeePosition storage ep = employeePositions[account];
require(ep.startTime == 0, 'vest: position already exists');
ep.startTime = startTime;
require((QUOTA - vestingAssets) >= amount, 'vest: not enough assets available');
ep.total = amount;
vestingAssets += amount;
emit LogNewVest(account, amount);
}
|
0.8.4
|
/// @notice owner can withdraw excess tokens
/// @param amount amount to be withdrawns
|
function withdraw(uint256 amount) external onlyOwner {
( , , uint256 available ) = globallyUnlocked();
require(amount <= available, 'withdraw: not enough assets available');
// Need to accoount for the withdrawn assets, they are no longer available
// in the employee pool
vestingAssets += amount;
distributer.mint(msg.sender, amount);
emit LogWithdrawal(msg.sender, amount);
}
|
0.8.4
|
/// @notice claim an amount of tokens
/// @param amount amount to be claimed
|
function claim(uint256 amount) external override {
require(amount > 0, "claim: No amount specified");
(uint256 unlocked, uint256 available, , ) = unlockedBalance(msg.sender);
require(available >= amount, "claim: Not enough user assets available");
uint256 _withdrawn = unlocked - available + amount;
EmployeePosition storage ep = employeePositions[msg.sender];
ep.withdrawn = _withdrawn;
distributer.mint(msg.sender, amount);
emit LogClaimed(msg.sender, amount, _withdrawn, available - amount);
}
|
0.8.4
|
/// @notice stops an employees vesting position
/// @param employee employees account
|
function stopVesting(address employee) external onlyOwner {
(uint256 unlocked, uint256 available, uint256 startTime, ) = unlockedBalance(employee);
require(startTime > 0, 'stopVesting: No position for user');
EmployeePosition storage ep = employeePositions[employee];
vestingAssets -= ep.total - unlocked;
ep.stopTime = block.timestamp;
ep.total = unlocked;
emit LogStoppedVesting(employee, unlocked, available);
}
|
0.8.4
|
/// @notice see the amount of vested assets the account has accumulated
/// @param account Account to get vested amount for
|
function unlockedBalance(address account)
internal
view
override
returns ( uint256, uint256, uint256, uint256 )
{
EmployeePosition storage ep = employeePositions[account];
uint256 startTime = ep.startTime;
if (block.timestamp < startTime + VESTING_CLIFF) {
return (0, 0, startTime, startTime + VESTING_TIME);
}
uint256 unlocked;
uint256 available;
uint256 stopTime = ep.stopTime;
uint256 _endTime = startTime + VESTING_TIME;
uint256 total = ep.total;
if (stopTime > 0) {
unlocked = total;
_endTime = stopTime;
} else if (block.timestamp < _endTime) {
unlocked = total * (block.timestamp - startTime) / (VESTING_TIME);
} else {
unlocked = total;
}
available = unlocked - ep.withdrawn;
return (unlocked, available, startTime, _endTime);
}
|
0.8.4
|
// Transfer a part to an address
|
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// No cap on number of parts
// Very unlikely to ever be 2^256 parts owned by one account
// Shouldn't waste gas checking for overflow
// no point making it less than a uint --> mappings don't pack
addressToTokensOwned[_to]++;
// transfer ownership
partIndexToOwner[_tokenId] = _to;
// New parts are transferred _from 0x0, but we can't account that address.
if (_from != address(0)) {
addressToTokensOwned[_from]--;
// clear any previously approved ownership exchange
delete partIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
|
0.4.20
|
// helper functions adapted from Jossie Calderon on stackexchange
|
function stringToUint32(string s) internal pure returns (uint32) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
if (b[i] >= 48 && b[i] <= 57) {
result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -.
}
}
return uint32(result);
}
|
0.4.20
|
/// internal function which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
|
function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) {
require(_tokenIds.length > 0);
for (uint i = 0; i < _tokenIds.length; i++) {
if (partIndexToOwner[_tokenIds[i]] != _owner) {
return false;
}
}
return true;
}
|
0.4.20
|
// transfers a part to another account
|
function transfer(address _to, uint256 _tokenId) public whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// Safety checks to prevent accidental transfers to common accounts
require(_to != address(0));
require(_to != address(this));
// can't transfer parts to the auction contract directly
require(_to != address(auction));
// can't transfer parts to any of the battle contracts directly
for (uint j = 0; j < approvedBattles.length; j++) {
require(_to != approvedBattles[j]);
}
// Cannot send tokens you don't own
require(owns(msg.sender, _tokenId));
// perform state changes necessary for transfer
_transfer(msg.sender, _to, _tokenId);
}
|
0.4.20
|
// approves the (_to) address to use the transferFrom function on the token with id (_tokenId)
// if you want to clear all approvals, simply pass the zero address
|
function approve(address _to, uint256 _deedId) external whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// use internal function?
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _deedId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_deedId] = _to;
Approval(msg.sender, _to, _deedId);
}
|
0.4.20
|
// approves many token ids
|
function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable {
for (uint i = 0; i < _tokenIds.length; i++) {
uint _tokenId = _tokenIds[i];
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _tokenId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_tokenId] = _to;
//create event for each approval? _tokenId guaranteed to hold correct value?
Approval(msg.sender, _to, _tokenId);
}
}
|
0.4.20
|
// transfer the part with id (_tokenId) from (_from) to (_to)
// (_to) must already be approved for this (_tokenId)
|
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused {
// Safety checks to prevent accidents
require(_to != address(0));
require(_to != address(this));
// sender must be approved
require(partIndexToApproved[_tokenId] == msg.sender);
// from must currently own the token
require(owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
|
0.4.20
|
// This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract
// as it is very gas hungry.
|
function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) {
uint256 tokenCount = balanceOf(_owner);
uint resultIndex = 0;
bytes24[] memory result = new bytes24[](tokenCount);
for (uint partId = _start; partId < _start + _numToSearch; partId++) {
if (partIndexToOwner[partId] == _owner) {
result[resultIndex] = _partToBytes(parts[partId]);
resultIndex++;
}
}
return result; // will have 0 elements if tokenCount == 0
}
|
0.4.20
|
// every level, you need 1000 more exp to go up a level
|
function getLevel(uint32 _exp) public pure returns(uint32) {
uint32 c = 0;
for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) {
c++;
}
return c;
}
|
0.4.20
|
// code duplicated
|
function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){
// The index should be valid.
require(_index < balanceOf(_owner));
// can loop through all without
uint256 seen = 0;
uint256 totalTokens = totalSupply();
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
}
|
0.4.20
|
// sum of perks (excluding prestige)
|
function _sumActivePerks(uint8[32] _perks) internal pure returns (uint256) {
uint32 sum = 0;
//sum from after prestige_index, to count+1 (for prestige index).
for (uint8 i = PRESTIGE_INDEX+1; i < PERK_COUNT+1; i++) {
sum += _perks[i];
}
return sum;
}
|
0.4.20
|
// you can unlock a new perk every two levels (including prestige when possible)
|
function choosePerk(uint8 _i) external {
require((_i >= PRESTIGE_INDEX) && (_i < PERK_COUNT+1));
User storage currentUser = addressToUser[msg.sender];
uint256 _numActivePerks = _sumActivePerks(currentUser.perks);
bool canPrestige = (_numActivePerks == PERK_COUNT);
//add prestige value to sum of perks
_numActivePerks += currentUser.perks[PRESTIGE_INDEX] * PERK_COUNT;
require(_numActivePerks < getLevel(currentUser.experience) / 2);
if (_i == PRESTIGE_INDEX) {
require(canPrestige);
_prestige();
} else {
require(_isValidPerkToAdd(currentUser.perks, _i));
_addPerk(_i);
}
PerkChosen(msg.sender, _i);
}
|
0.4.20
|
// Calculates price and transfers purchase to owner. Part is NOT transferred to buyer.
|
function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) {
Auction storage auction = tokenIdToAuction[_partId];
// check that this token is being auctioned
require(_isActiveAuction(auction));
// enforce purchase >= the current price
uint256 price = _currentPrice(auction);
require(_purchaseAmount >= price);
// Store seller before we delete auction.
address seller = auction.seller;
// Valid purchase. Remove auction to prevent reentrancy.
_removeAuction(_partId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate and take fee from purchase
uint256 auctioneerCut = _computeFee(price);
uint256 sellerProceeds = price - auctioneerCut;
PrintEvent("Seller, proceeds", seller, sellerProceeds);
// Pay the seller
seller.transfer(sellerProceeds);
}
// Calculate excess funds and return to buyer.
uint256 purchaseExcess = _purchaseAmount - price;
PrintEvent("Sender, excess", msg.sender, purchaseExcess);
// Return any excess funds. Reentrancy again prevented by deleting auction.
msg.sender.transfer(purchaseExcess);
AuctionSuccessful(_partId, price, msg.sender);
return price;
}
|
0.4.20
|
// computes the current price of an deflating-price auction
|
function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) {
_price = _startPrice;
if (_secondsPassed >= _duration) {
// Has been up long enough to hit endPrice.
// Return this price floor.
_price = _endPrice;
// this is a statically price sale. Just return the price.
}
else if (_duration > 0) {
// This auction contract supports auctioning from any valid price to any other valid price.
// This means the price can dynamically increase upward, or downard.
int256 priceDifference = int256(_endPrice) - int256(_startPrice);
int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startPrice) + currentPriceDifference;
_price = uint256(currentPrice);
}
return _price;
}
|
0.4.20
|
// Creates an auction and lists it.
|
function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration, address _seller ) external whenNotPaused {
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startPrice == uint256(uint128(_startPrice)));
require(_endPrice == uint256(uint128(_endPrice)));
require(_duration == uint256(uint64(_duration)));
require(_startPrice >= _endPrice);
require(msg.sender == address(nftContract));
_escrow(_seller, _partId);
Auction memory auction = Auction(
_seller,
uint128(_startPrice),
uint128(_endPrice),
uint64(_duration),
uint64(now) //seconds uint
);
PrintEvent("Auction Start", 0x0, auction.start);
_newAuction(_partId, auction);
}
|
0.4.20
|
// Purchases an open auction
// Will transfer ownership if successful.
|
function purchase(uint256 _partId) external payable whenNotPaused {
address seller = tokenIdToAuction[_partId].seller;
// _purchase will throw if the purchase or funds transfer fails
uint256 price = _purchase(_partId, msg.value);
_transfer(msg.sender, _partId);
// If the seller is the scrapyard, track price information.
if (seller == address(nftContract)) {
lastScrapPrices[scrapCounter] = price;
if (scrapCounter == LAST_CONSIDERED - 1) {
scrapCounter = 0;
} else {
scrapCounter++;
}
}
}
|
0.4.20
|
// Returns the details of an auction from its _partId.
|
function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start);
}
|
0.4.20
|
// list a part for auction.
|
function createAuction(
uint256 _partId,
uint256 _startPrice,
uint256 _endPrice,
uint256 _duration ) external whenNotPaused
{
// user must have current control of the part
// will lose control if they delegate to the auction
// therefore no duplicate auctions!
require(owns(msg.sender, _partId));
_approve(_partId, auction);
// will throw if inputs are invalid
// will clear transfer approval
DutchAuction(auction).createAuction(_partId,_startPrice,_endPrice,_duration,msg.sender);
}
|
0.4.20
|
/// An internal method that creates a new part 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 Forge event
/// and a Transfer event.
|
function _createPart(uint8[4] _partArray, address _owner) internal returns (uint) {
uint32 newPartId = uint32(parts.length);
assert(newPartId == parts.length);
Part memory _part = Part({
tokenId: newPartId,
partType: _partArray[0],
partSubType: _partArray[1],
rarity: _partArray[2],
element: _partArray[3],
battlesLastDay: 0,
experience: 0,
forgeTime: uint32(now),
battlesLastReset: uint32(now)
});
assert(newPartId == parts.push(_part) - 1);
// emit the FORGING!!!
Forge(_owner, newPartId, _part);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPartId);
return newPartId;
}
|
0.4.20
|
// uint8[] public defenceElementBySubtypeIndex = [1,2,4,3,4,1,3,3,2,1,4];
// uint8[] public meleeElementBySubtypeIndex = [3,1,3,2,3,4,2,2,1,1,1,1,4,4];
// uint8[] public bodyElementBySubtypeIndex = [2,1,2,3,4,3,1,1,4,2,3,4,1,0,1]; // no more lambos :'(
// uint8[] public turretElementBySubtypeIndex = [4,3,2,1,2,1,1,3,4,3,4];
|
function setRewardChance(uint _newChance) external onlyOwner {
require(_newChance > 980); // not too hot
require(_newChance <= 1000); // not too cold
PART_REWARD_CHANCE = _newChance; // just right
// come at me goldilocks
}
|
0.4.20
|
// function _randomIndex(uint _rand, uint8 _startIx, uint8 _endIx, uint8 _modulo) internal pure returns (uint8) {
// require(_startIx < _endIx);
// bytes32 randBytes = bytes32(_rand);
// uint result = 0;
// for (uint8 i=_startIx; i<_endIx; i++) {
// result = result | uint8(randBytes[i]);
// result << 8;
// }
// uint8 resultInt = uint8(uint(result) % _modulo);
// return resultInt;
// }
// This function takes a random uint, an owner and randomly generates a valid part.
// It then transfers that part to the owner.
|
function _generateRandomPart(uint _rand, address _owner) internal {
// random uint 20 in length - MAYBE 20.
// first randomly gen a part type
_rand = uint(keccak256(_rand));
uint8[4] memory randomPart;
randomPart[0] = uint8(_rand % 4) + 1;
_rand = uint(keccak256(_rand));
// randomPart[0] = _randomIndex(_rand,0,4,4) + 1; // 1, 2, 3, 4, => defence, melee, body, turret
if (randomPart[0] == DEFENCE) {
randomPart[1] = _getRandomPartSubtype(_rand,defenceElementBySubtypeIndex);
randomPart[3] = _getElement(defenceElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == MELEE) {
randomPart[1] = _getRandomPartSubtype(_rand,meleeElementBySubtypeIndex);
randomPart[3] = _getElement(meleeElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == BODY) {
randomPart[1] = _getRandomPartSubtype(_rand,bodyElementBySubtypeIndex);
randomPart[3] = _getElement(bodyElementBySubtypeIndex, randomPart[1]);
} else if (randomPart[0] == TURRET) {
randomPart[1] = _getRandomPartSubtype(_rand,turretElementBySubtypeIndex);
randomPart[3] = _getElement(turretElementBySubtypeIndex, randomPart[1]);
}
_rand = uint(keccak256(_rand));
randomPart[2] = _getRarity(_rand);
// randomPart[2] = _getRarity(_randomIndex(_rand,8,12,3)); // rarity
_createPart(randomPart, _owner);
}
|
0.4.20
|
// scraps a part for shards
|
function scrap(uint partId) external {
require(owns(msg.sender, partId));
User storage u = addressToUser[msg.sender];
_addShardsToUser(u, (SHARDS_TO_PART * scrapPercent) / 100);
Scrap(msg.sender, partId);
// this doesn't need to be secure
// no way to manipulate it apart from guaranteeing your parts are resold
// or burnt
if (uint(keccak256(scrapCount)) % 100 >= burnRate) {
_transfer(msg.sender, address(this), partId);
_createScrapPartAuction(partId);
} else {
_transfer(msg.sender, address(0), partId);
}
scrapCount++;
}
|
0.4.20
|
// store the part information of purchased crates
|
function openAll() public {
uint len = addressToPurchasedBlocks[msg.sender].length;
require(len > 0);
uint8 count = 0;
// len > i to stop predicatable wraparound
for (uint i = len - 1; i >= 0 && len > i; i--) {
uint crateBlock = addressToPurchasedBlocks[msg.sender][i];
require(block.number > crateBlock);
// can't open on the same timestamp
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
userToRobots[msg.sender].push(rand);
count++;
} else {
// all others will be expired
expiredCrates[msg.sender] += (i + 1);
break;
}
}
CratesOpened(msg.sender, count);
delete addressToPurchasedBlocks[msg.sender];
}
|
0.4.20
|
// convert old string representation of robot into 4 new ERC721 parts
|
function _convertBlueprint(string original) pure private returns(uint8[4] body,uint8[4] melee, uint8[4] turret, uint8[4] defence ) {
/* ------ CONVERSION TIME ------ */
body[0] = BODY;
body[1] = _getPartId(original, 3, 5, 15);
body[2] = _getRarity(original, 0, 3);
body[3] = _getElement(BODY_ELEMENT_BY_ID, body[1]);
turret[0] = TURRET;
turret[1] = _getPartId(original, 8, 10, 11);
turret[2] = _getRarity(original, 5, 8);
turret[3] = _getElement(TURRET_ELEMENT_BY_ID, turret[1]);
melee[0] = MELEE;
melee[1] = _getPartId(original, 13, 15, 14);
melee[2] = _getRarity(original, 10, 13);
melee[3] = _getElement(MELEE_ELEMENT_BY_ID, melee[1]);
defence[0] = DEFENCE;
var len = bytes(original).length;
// string of number does not have preceding 0's
if (len == 20) {
defence[1] = _getPartId(original, 18, 20, 11);
} else if (len == 19) {
defence[1] = _getPartId(original, 18, 19, 11);
} else { //unlikely to have length less than 19
defence[1] = uint8(1);
}
defence[2] = _getRarity(original, 15, 18);
defence[3] = _getElement(DEFENCE_ELEMENT_BY_ID, defence[1]);
// implicit return
}
|
0.4.20
|
// Users can open pending crates on the new contract.
|
function openCrates() public whenNotPaused {
uint[] memory pc = pendingCrates[msg.sender];
require(pc.length > 0);
uint8 count = 0;
for (uint i = 0; i < pc.length; i++) {
uint crateBlock = pc[i];
require(block.number > crateBlock);
// can't open on the same timestamp
var hash = block.blockhash(crateBlock);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i)) % (10 ** 20);
_migrateRobot(uintToString(rand));
count++;
}
}
CratesOpened(msg.sender, count);
delete pendingCrates[msg.sender];
}
|
0.4.20
|
// in PerksRewards
|
function redeemBattleCrates() external {
uint8 count = 0;
uint len = pendingRewards[msg.sender].length;
require(len > 0);
for (uint i = 0; i < len; i++) {
Reward memory rewardStruct = pendingRewards[msg.sender][i];
// can't open on the same timestamp
require(block.number > rewardStruct.blocknumber);
// ensure user has converted all pendingRewards
require(rewardStruct.blocknumber != 0);
var hash = block.blockhash(rewardStruct.blocknumber);
if (uint(hash) != 0) {
// different results for all different crates, even on the same block/same user
// randomness is already taken care of
uint rand = uint(keccak256(hash, msg.sender, i));
_generateBattleReward(rand,rewardStruct.exp);
count++;
} else {
// Do nothing, no second chances to secure integrity of randomness.
}
}
CratesOpened(msg.sender, count);
delete pendingRewards[msg.sender];
}
|
0.4.20
|
// don't need to do any scaling
// should already have been done by previous stages
|
function _addUserExperience(address user, int32 exp) internal {
// never allow exp to drop below 0
User memory u = addressToUser[user];
if (exp < 0 && uint32(int32(u.experience) + exp) > u.experience) {
u.experience = 0;
return;
} else if (exp > 0) {
// check for overflow
require(uint32(int32(u.experience) + exp) > u.experience);
}
addressToUser[user].experience = uint32(int32(u.experience) + exp);
//_addUserReward(user, exp);
}
|
0.4.20
|
//requires parts in order
|
function hasOrderedRobotParts(uint[] partIds) external view returns(bool) {
uint len = partIds.length;
if (len != 4) {
return false;
}
for (uint i = 0; i < len; i++) {
if (parts[partIds[i]].partType != i+1) {
return false;
}
}
return true;
}
|
0.4.20
|
/*
* @notice Mints specified amount of tokens on the public sale
* @dev Non reentrant. Emits PublicSaleMint event
* @param _amount Amount of tokens to mint
*/
|
function publicSaleMint(uint256 _amount) external payable nonReentrant whenNotPaused {
require(saleState == 3, "public sale isn't active");
require(_amount > 0 && _amount <= publicSaleLimitPerTx, "invalid amount");
uint256 maxTotalSupply_ = maxTotalSupply;
uint256 totalSupply_ = totalSupply();
require(totalSupply_ + _amount <= maxTotalSupply_, "already sold out");
require(mintCounter + _amount <= maxTotalSupply_ - amountForGiveAway, "the rest is reserved");
_buyAndRefund(_amount, publicSalePrice);
if (totalSupply_ + _amount == maxTotalSupply_) emit SoldOut();
emit PublicSaleMint(_msgSender(), _amount);
}
|
0.8.5
|
/*
* @notice Mints specified IDs to specified addresses
* @dev Only owner can call it. Lengths of arrays must be equal.
* @param _accounts The list of addresses to mint tokens to
*/
|
function giveaway(address[] memory _accounts) external onlyOwner {
uint256 maxTotSup = maxTotalSupply;
uint256 currentTotalSupply = totalSupply();
require(_accounts.length <= publicSaleLimitPerTx, "Limit per transaction exceeded");
require(airdropCounter + _accounts.length <= amountForGiveAway, "limit for airdrop exceeded");
require(currentTotalSupply + _accounts.length <= maxTotSup, "maxTotalSupply exceeded");
uint256 counter = currentTotalSupply;
for (uint256 i; i < _accounts.length; i++) {
_safeMint(_accounts[i], uint8(1));
counter++;
}
airdropCounter += uint16(_accounts.length);
if (currentTotalSupply + _accounts.length == maxTotSup) emit SoldOut(); // emit SoldOut in case some tokens were airdropped after the sale
emit GiveAway(_accounts);
}
|
0.8.5
|
/*
* @dev The main logic for the pre sale mint. Emits PreSaleMint event
* @param _amount The amount of tokens
*/
|
function _preSaleMintVipPl(uint256 _amount) private {
require(saleState == 1, "VIP Presale isn't active");
require(_amount > 0, "invalid amount");
require(preSaleMintedVipPl[_msgSender()] + _amount <= preSaleLimitPerUserVipPl, "limit per user exceeded");
uint256 totalSupply_ = totalSupply();
require(totalSupply_ + _amount <= preSaleTokenLimit, "presale token limit exceeded");
_buyAndRefund(_amount, preSaleVipPlPrice);
preSaleMintedVipPl[_msgSender()] += uint8(_amount);
emit PreSaleMintVipPl(_msgSender(), _amount);
}
|
0.8.5
|
/*
* @dev Mints tokens for the user and refunds ETH if too much was passed
* @param _amount The amount of tokens
* @param _price The price for each token
*/
|
function _buyAndRefund(uint256 _amount, uint256 _price) internal {
uint256 totalCost = _amount * _price;
require(msg.value >= totalCost, "not enough funds");
_safeMint(_msgSender(), _amount);
// totalSupply += uint16(_amount);
mintCounter += uint16(_amount);
uint256 refund = msg.value - totalCost;
if (refund > 0) {
_sendETH(payable(_msgSender()), refund);
}
}
|
0.8.5
|
// METHODS
// constructor is given number of sigs required to do protected "onlymanyowners" transactions
// as well as the selection of addresses capable of confirming them (msg.sender is not added to the owners!).
|
function multiowned(address[] _owners, uint _required)
validNumOwners(_owners.length)
multiOwnedValidRequirement(_required, _owners.length)
{
assert(c_maxOwners <= 255);
m_numOwners = _owners.length;
m_multiOwnedRequired = _required;
for (uint i = 0; i < _owners.length; ++i)
{
address owner = _owners[i];
// invalid and duplicate addresses are not allowed
require(0 != owner && !isOwner(owner) /* not isOwner yet! */);
uint currentOwnerIndex = checkOwnerIndex(i + 1 /* first slot is unused */);
m_owners[currentOwnerIndex] = owner;
m_ownerIndex[owner] = currentOwnerIndex;
}
assertOwnersAreConsistent();
}
|
0.4.18
|
// All pending operations will be canceled!
|
function removeOwner(address _owner)
external
ownerExists(_owner)
validNumOwners(m_numOwners - 1)
multiOwnedValidRequirement(m_multiOwnedRequired, m_numOwners - 1)
onlymanyowners(sha3(msg.data))
{
assertOwnersAreConsistent();
clearPending();
uint ownerIndex = checkOwnerIndex(m_ownerIndex[_owner]);
m_owners[ownerIndex] = 0;
m_ownerIndex[_owner] = 0;
//make sure m_numOwners is equal to the number of owners and always points to the last owner
reorganizeOwners();
assertOwnersAreConsistent();
OwnerRemoved(_owner);
}
|
0.4.18
|
// Reclaims free slots between valid owners in m_owners.
// TODO given that its called after each removal, it could be simplified.
|
function reorganizeOwners() private {
uint free = 1;
while (free < m_numOwners)
{
// iterating to the first free slot from the beginning
while (free < m_numOwners && m_owners[free] != 0) free++;
// iterating to the first occupied slot from the end
while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--;
// swap, if possible, so free slot is located at the end after the swap
if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0)
{
// owners between swapped slots should't be renumbered - that saves a lot of gas
m_owners[free] = m_owners[m_numOwners];
m_ownerIndex[m_owners[free]] = free;
m_owners[m_numOwners] = 0;
}
}
}
|
0.4.18
|
/**
* @dev transfer tokens to the specified address
* @param _to The address to transfer to
* @param _value The amount to be transferred
* @return bool A successful transfer returns true
*/
|
function transfer(address _to, uint256 _value) returns (bool success) {
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;
}
|
0.4.16
|
// ------------------------------------------------------------------------
// 100 BFCL Tokens per 1 ETH
// ------------------------------------------------------------------------
|
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 360;
} else {
tokens = msg.value * 300;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
|
0.4.24
|
// ============ Main View Functions ==============
|
function getPools(string[] calldata poolIds)
external
view
override
returns (address[] memory poolAddresses)
{
poolAddresses = new address[](poolIds.length);
for (uint256 i = 0; i < poolIds.length; i++) {
poolAddresses[i] = pools[poolIds[i]];
}
}
|
0.7.6
|
/**
* @dev transfer tokens from one address to another
* @param _from address The address that you want to send tokens from
* @param _to address The address that you want to transfer to
* @param _value uint256 The amount to be transferred
* @return bool A successful transfer returns true
*/
|
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
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;
}
|
0.4.16
|
/**
* @dev Extend parent behavior requiring beneficiary to be in whitelist.
* @param _beneficiary Token beneficiary
* @param _weiAmount Amount of wei contributed
*/
|
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
whenNotPaused
{
super._preValidatePurchase(_beneficiary, _weiAmount);
if(block.timestamp <= openingTime + (2 weeks)) {
require(whitelist[_beneficiary]);
require(msg.value >= 5 ether);
rate = 833;
}else if(block.timestamp > openingTime + (2 weeks) && block.timestamp <= openingTime + (3 weeks)) {
require(msg.value >= 5 ether);
rate = 722;
}else if(block.timestamp > openingTime + (3 weeks) && block.timestamp <= openingTime + (4 weeks)) {
require(msg.value >= 5 ether);
rate = 666;
}else if(block.timestamp > openingTime + (4 weeks) && block.timestamp <= openingTime + (5 weeks)) {
require(msg.value >= 5 ether);
rate = 611;
}else{
rate = 555;
}
}
|
0.4.24
|
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
|
function _forwardFunds()
internal
{
// referer bonus
if(msg.data.length == 20) {
address referrerAddress = bytesToAddres(bytes(msg.data));
require(referrerAddress != address(token) && referrerAddress != msg.sender);
uint256 referrerAmount = msg.value.mul(REFERRER_PERCENT).div(100);
referrers[referrerAddress] = referrers[referrerAddress].add(referrerAmount);
}
if(block.timestamp <= openingTime + (2 weeks)) {
wallet.transfer(msg.value);
}else{
vault.deposit.value(msg.value)(msg.sender);
}
}
|
0.4.24
|
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _numOfWinners Number of winners in the pool
* @param _participantLimit Maximum number of paricipants
* @param _enterAmount Exact amount to enter this pool
* @param _feePercentage Manager fee of this pool
* @param _randomSeed Seed for Random Number Generation
*/
|
function setPoolRules(
uint256 _numOfWinners,
uint256 _participantLimit,
uint256 _enterAmount,
uint256 _feePercentage,
uint256 _randomSeed
) external onlyOwner {
require(poolStatus == PoolStatus.NOTSTARTED, "in progress");
require(_numOfWinners != 0, "invalid numOfWinners");
require(_numOfWinners < _participantLimit, "too much numOfWinners");
poolConfig = PoolConfig(
_numOfWinners,
_participantLimit,
_enterAmount,
_feePercentage,
_randomSeed,
block.timestamp
);
poolStatus = PoolStatus.INPROGRESS;
emit PoolStarted(
_participantLimit,
_numOfWinners,
_enterAmount,
_feePercentage,
block.timestamp
);
}
|
0.6.10
|
/*
* Function to mint NFTs
*/
|
function mint(address to, uint32 count) internal {
if (count > 1) {
uint256[] memory ids = new uint256[](uint256(count));
uint256[] memory amounts = new uint256[](uint256(count));
for (uint32 i = 0; i < count; i++) {
ids[i] = totalSupply + i;
amounts[i] = 1;
}
_mintBatch(to, ids, amounts, "");
} else {
_mint(to, totalSupply, 1, "");
}
totalSupply += count;
}
|
0.8.7
|
/*
* Function to withdraw collected amount during minting by the owner
*/
|
function withdraw(
address _to
)
public
onlyOwner
{
uint balance = address(this).balance;
require(balance > 0, "Balance should be more then zero");
if(balance <= devSup) {
payable(devAddress).transfer(balance);
devSup = devSup.sub(balance);
return;
} else {
if(devSup > 0) {
payable(devAddress).transfer(devSup);
balance = balance.sub(devSup);
devSup = 0;
}
payable(_to).transfer(balance);
}
}
|
0.8.7
|
/*
* Function to mint new NFTs during the public sale
* It is payable. Amount is calculated as per (NFTPrice.mul(_numOfTokens))
*/
|
function mintNFT(
uint32 _numOfTokens
)
public
payable
{
require(isActive, 'Contract is not active');
require(!isPrivateSaleActive, 'Private sale still active');
require(!isPresaleActive, 'Presale still active');
require(totalSupply.add(_numOfTokens).sub(giveawayCount) <= MAX_NFT_PUBLIC, "Purchase would exceed max public supply of NFTs");
require(msg.value >= NFTPrice.mul(_numOfTokens), "Ether value sent is not correct");
mint(msg.sender,_numOfTokens);
}
|
0.8.7
|
/*
* Function to mint new NFTs during the private sale & presale
* It is payable.
*/
|
function mintNFTDuringPresale(
uint32 _numOfTokens,
bytes32[] memory _proof
)
public
payable
{
require(isActive, 'Contract is not active');
require(verify(_proof, bytes32(uint256(uint160(msg.sender)))), "Not whitelisted");
if (!isPresaleActive) {
require(isPrivateSaleActive, 'Private sale not active');
require(msg.value >= privateSalePrice.mul(_numOfTokens), "Ether value sent is not correct");
require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase');
mint(msg.sender,_numOfTokens);
nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens);
return;
}
require(msg.value >= presalePrice.mul(_numOfTokens), "Ether value sent is not correct");
require(nftBalances[msg.sender].add(_numOfTokens)<= maxPerWalletPresale, 'Max per wallet reached for this phase');
mint(msg.sender,_numOfTokens);
nftBalances[msg.sender] = nftBalances[msg.sender].add(_numOfTokens);
}
|
0.8.7
|
/*
* Function to mint all NFTs for giveaway and partnerships
*/
|
function mintMultipleByOwner(
address[] memory _to
)
public
onlyOwner
{
require(totalSupply.add(_to.length) < MAX_NFT, "Tokens number to mint cannot exceed number of MAX tokens");
require(giveawayCount.add(_to.length)<=maxGiveaway,"Cannot do that much giveaway");
for(uint256 i = 0; i < _to.length; i++){
mint(_to[i],1);
}
giveawayCount=giveawayCount.add(_to.length);
}
|
0.8.7
|
/*
* Function to verify the proof
*/
|
function verify(bytes32[] memory proof, bytes32 leaf) public view 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 = sha256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = sha256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
|
0.8.7
|
/**
* Enter pool with ETH
*/
|
function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) {
require(msg.value == poolConfig.enterAmount, "insufficient amount");
if (!_isEthPool()) {
revert("not accept ETH");
}
// wrap ETH to WETH
IWETH(controller.getWeth()).deposit{ value: msg.value }();
return _enterPool();
}
|
0.6.10
|
/**
* @dev Set time of dividend Payments.
* @return Start_reward
*/
|
function dividendPaymentsTime (uint256 _start) public onlyOwner returns (uint256 Start_reward, uint256 End_reward) {
uint256 check_time = block.timestamp;
require (check_time < _start, "WRONG TIME, LESS THEM CURRENT");
// require (check_time < _start.add(2629743), "ONE MONTH BEFORE THE START OF PAYMENTS");
dividend_start = _start;
dividend_end = dividend_start.add(2629743);
return (dividend_start, dividend_end);
}
|
0.5.16
|
/*@dev call _token_owner address
* @return Revard _dividend
* private function dividend withdraw
*/
|
function reward () public view returns (uint256 Reward) {
uint256 temp_allowance = project_owner.balance;
require(temp_allowance > 0, "BALANCE IS EMPTY");
require(balances[msg.sender] != 0, "ZERO BALANCE");
uint256 temp_Fas_count = balances[msg.sender];
uint256 _percentage = temp_Fas_count.mul(100000).div(totalSupply);
uint256 _dividend = temp_allowance.mul(_percentage).div(100000);
return _dividend;
}
|
0.5.16
|
/**
* Distribution of benefits
* param _token_owner Divider's Token address
* binds the time stamp of receipt of dividends in struct 'Holder' to
* 'holders' to exclude multiple receipt of dividends, valid for 30 days.
* Dividends are received once a month.
* Dividends are debited from the Treasury address.
* The Treasury is replenished with ether depending on the results of the company's work.
*/
|
function dividendToReward() internal {
uint256 temp_allowance = project_owner.balance;
require(balances[msg.sender] != 0, "ZERO BALANCE");
require(temp_allowance > 0, "BALANCE IS EMPTY");
uint256 withdraw_time = block.timestamp;
require (withdraw_time > dividend_start, "PAYMENTS HAVEN'T STARTED YET");
require (withdraw_time < dividend_end, "PAYMENTS HAVE ALREADY ENDED");
uint256 period = withdraw_time.sub(holders[msg.sender].rewardWithdrawTime);
require (period > 2505600, "DIVIDENDS RECIEVED ALREADY");
dividend = reward ();
holders[msg.sender].rewardWithdrawTime = withdraw_time;
}
|
0.5.16
|
/**@dev New member accepts the invitation of the Board of Directors.
* param Owner_Id used to confirm your consent to the invitation
* to the Board of Directors of the company valid for 24 hours.
* if the Owner_Id is not used during the day, the invitation is canceled
* 'Owner_Id' is deleted.
* only a new member of the company's Board of Directors has access to the function call
*/
|
function acceptOwnership() public {
address new_owner = temporary_address;
require(msg.sender == new_owner, "ACCESS DENIED");
uint256 time_accept = block.timestamp;
difference_time = time_accept - acception_Id;
if (difference_time < 86400){
FASList.push(new_owner);
Fas_number++;
}
else{
delete owners[new_owner];
delete FasID[acception_Id].owner_address;
}
}
|
0.5.16
|
/**@dev Removes a member from the company's Board of Directors.
* param address_owner this is the address of the Board member being
* removed. Only the project owner has access to call the function.
* The 'project_owner' cannot be deleted.
*/
|
function delOwner (address address_owner) public {
require(msg.sender == project_owner, "ACCESS DENIED");
require (address_owner != project_owner, "IT IS IMPOSSIBLE TO REMOVE PROJECT OWNER");
uint256 Id_toDel = owners[address_owner].ID;
delete owners[address_owner];
delete FasID[Id_toDel].owner_address;
uint256 new_FASListLength = FASList.length;
new_FASListLength--;
uint256 index_array_del;
address [] memory _FASList = new address[](new_FASListLength);
for (uint256 j = 0; j< Fas_number; j++){
if (FASList[j] == address_owner){
index_array_del = j;
}
}
for (uint256 i = 0; i< new_FASListLength; i++){
if (i < index_array_del){
_FASList[i] = FASList[i];
}
else
{
_FASList[i] = FASList[i+1];
}
}
Fas_number--;
FASList = _FASList;
}
|
0.5.16
|
/**Invitation of a new member of the company's Board of Directors.
* Only the project owner has access to the function call.
* param _to address of the invited member of the company's Board of Directors
* A new member of the company's Board of Directors receives 'Owner_Id'.
*/
|
function newOwnerInvite(address _to) public {
require (msg.sender == project_owner, "ACCESS DENIED");
require (balances[_to]>0, "ZERO BALANCE");
for (uint256 j = 0; j< Fas_number; j++){
require (FASList[j] != _to);
}
beforeNewOwnerInvite(_to);
acception_Id = block.timestamp;
temporary_address = _to;
}
|
0.5.16
|
/** @dev Function to start the voting process. Call access only project_owner.
* Clears the previous result of the vote. Sets a time stamp for the
* start of voting.
* @return votes_num
*/
|
function createVote() public returns (uint256){
require (msg.sender == project_owner, "ACCESS DENIED");
votes_num = votes_num.add(1);
vote_start = block.timestamp;
voteEndTime = vote_start.add(voting_period);
voteResult_Agree = 0;
voteResult_Dissagree = 0;
lastVoteResult = [0, 0, 0, 0, 0];
return votes_num;
}
|
0.5.16
|
/**
* vote for a given votes_num
* param Owner_Id the given rights to vote
* param _vote_status_value uint256 the vote of status, 1 Agree, 0 Disagree
* Only a member of the company's Board of Directors has the right to vote.
* You can only vote once during the voting period
*/
|
function vote(uint256 Owner_Id, uint256 _vote_status_value) public{
require(_vote_status_value >= 0, "INPUT: 1 = AGREE, 0 = DISAGREE");
require(_vote_status_value <= 1, "INPUT: 1 = AGREE, 0 = DISAGREE");
uint256 voting_time = block.timestamp;
address check_address = FasID[Owner_Id].owner_address;
require (msg.sender == check_address, "ACCESS DENIED");
uint256 lastVotingOwnerCheck = voting_time.sub(FasID[Owner_Id].voted_time);
require(voting_time < voteEndTime, "THE VOTE IS ALREADY OVER");
require(voting_period < lastVotingOwnerCheck, "YOU HAVE ALREADY VOTED");
if(_vote_status_value == 0)
{
disagree = balances[check_address];
voteResult_Dissagree = voteResult_Dissagree.add(disagree);
FasID[Owner_Id].voted_time = voting_time;
}
if (_vote_status_value == 1)
{
agree = balances[check_address];
voteResult_Agree = voteResult_Agree.add(agree);
FasID[Owner_Id].voted_time = voting_time;
}
}
|
0.5.16
|
/**
* @dev Called only after the end of the voting time.
* @return the voting restult: vote_num, voteResult, quorum_summ, vote_start, vote_end
*/
|
function getVoteResult() public returns (uint256[] memory){
uint256 current_time = block.timestamp;
require (vote_start < current_time, "VOTING HAS NOT STARTED");
voteEndTime = vote_start.add(voting_period);
require (current_time > voteEndTime, "THE VOTE ISN'T OVER YET");
uint256 quorum_summ = voteResult_Agree.add(voteResult_Dissagree);
if(voteResult_Agree >= voteResult_Dissagree)
{
voteResult = 1;
}
if(voteResult_Agree < voteResult_Dissagree)
{
voteResult = 0;
}
lastVoteResult = [votes_num, voteResult, quorum_summ, vote_start, voteEndTime];
voteNum[votes_num].quorum = quorum_summ;
voteNum[votes_num].voting_result = voteResult;
voteNum[votes_num].voting_starts = vote_start;
voteNum[votes_num].voting_ends = voteEndTime;
vote_start = 0;
return lastVoteResult;
}
|
0.5.16
|
/**
* Reset the pool, clears the existing state variable values and the pool can be initialized again.
*/
|
function _resetPool() internal {
poolStatus = PoolStatus.INPROGRESS;
delete totalEnteredAmount;
delete rewardPerParticipant;
isRNDGenerated = false;
randomResult = 0;
areWinnersGenerated = false;
delete winnerIndexes;
delete participants;
emit PoolReset();
uint256 tokenBalance = enterToken.balanceOf(address(this));
if (tokenBalance > 0) {
_transferEnterToken(feeRecipient, tokenBalance);
}
}
|
0.6.10
|
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _numOfWinners Number of winners in the pool
* @param _participantLimit Maximum number of paricipants
* @param _rewardAmount Reward amount of this pool
* @param _randomSeed Seed for Random Number Generation
*/
|
function setPoolRules(
uint256 _numOfWinners,
uint256 _participantLimit,
uint256 _rewardAmount,
uint256 _randomSeed
) external onlyOwner {
require(poolStatus != PoolStatus.INPROGRESS, "in progress");
require(_numOfWinners != 0, "invalid numOfWinners");
require(_numOfWinners < _participantLimit, "too much numOfWinners");
poolConfig = PoolConfig(
_numOfWinners,
_participantLimit,
_rewardAmount,
_randomSeed,
block.timestamp
);
poolStatus = PoolStatus.INPROGRESS;
emit PoolStarted(
_participantLimit,
_numOfWinners,
_rewardAmount,
block.timestamp
);
}
|
0.6.10
|
/**
* @dev Emits event to mint a token to the senders adress
* @param _tokenId address of the future owner of the token
*/
|
function mintNFTWithID(uint256 _tokenId) public payable {
require(!_exists(_tokenId), "token_exists");
require(tx.gasprice * gasToMint <= msg.value, "min_price");
// pay owner the gas fee it needs to call mintTo
address payable payowner = address(uint160(owner()));
require(payowner.send( msg.value ), "fees_to_owner");
//→ emit event for off-chain listener
//emit NFTEvent(1, _tokenId, msg.sender, msg.value);
dao.mintNFTWithID(_tokenId, msg.sender, msg.value);
}
|
0.5.17
|
/**
* @dev Track token transfers / upgrade potentials
*/
|
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override {
super._beforeTokenTransfer(from, to, tokenId);
// Skip freshly minted tokens to save gas
if (from != address(0)) {
tokenTransferCounts[tokenId] += 1;
}
}
|
0.8.4
|
/**
* @dev Upgrade a token if it's ready
*/
|
function upgradeToken(uint256 tokenId) external {
require(_exists(tokenId), "Update nonexistent token");
require(_msgSender() == ERC721.ownerOf(tokenId), "Must own token for upgrade");
require(tokenLevels[tokenId] < tokenTransferCounts[tokenId], "Token is not ready for upgrade");
uint256 oldLevel = tokenLevels[tokenId];
uint256 newLevel = tokenTransferCounts[tokenId];
tokenLevels[tokenId] = newLevel;
emit TokenUpgraded(tokenId, newLevel, oldLevel);
}
|
0.8.4
|
/**
* @dev Return the mooncake text for a given tokenId and its level
*/
|
function getMooncakeTextWithLevel(uint256 tokenId, uint256 level) public view returns (string memory) {
uint8[6] memory slotIds = getMooncakeTextSlotIds(tokenId, level);
string memory output = slot0[slotIds[0]];
if (slotIds[1] < 255) {
output = string(abi.encodePacked(output, slot1[slotIds[1]]));
}
if (slotIds[2] < 255) {
output = string(abi.encodePacked(output, slot2[slotIds[2]]));
}
output = string(abi.encodePacked(output, STRING_MOONCAKE));
if (slotIds[3] < 255) {
output = string(abi.encodePacked(output, STRING_PRE_SLOT3, slot3[slotIds[3]]));
}
if (slotIds[4] < 255) {
output = string(abi.encodePacked(output, STRING_PRE_SLOT4, slot4[slotIds[4]]));
}
if (slotIds[5] < 255) {
output = string(abi.encodePacked(output, STRING_PRE_SLOT5, slot5[slotIds[5]]));
}
return output;
}
|
0.8.4
|
/**
* @dev Mint tokens
*/
|
function mintWithAffiliate(uint256 numberOfNfts, address affiliate) public payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp >= SALES_START_TIMESTAMP, "Not started");
require(numberOfNfts > 0, "Cannot mint 0 NFTs");
require(numberOfNfts <= 50, "Cannot mint more than 50 in 1 tx");
uint256 total = totalSupply();
require(total + numberOfNfts <= maxNftSupply, "Sold out");
require(msg.value == numberOfNfts * MINT_FEE, "Ether value sent is incorrect");
// Effects
for (uint256 i = 0; i < numberOfNfts; i++) {
uint256 tokenId = total + i;
_safeMint(_msgSender(), tokenId, "");
if (affiliate != address(0)) {
emit AffiliateMint(tokenId, affiliate);
}
}
}
|
0.8.4
|
/**
* @dev Claim a free one
*/
|
function claimOneFreeNft() external payable nonReentrant {
// Checks
require(!contractSealed, "Contract sealed");
require(block.timestamp >= CLAIM_START_TIMESTAMP, "Not started");
uint256 total = totalSupply();
require(total + 1 <= maxNftSupply, "Sold out");
require(numFreeMints + 1 <= maxFreeMints, "No more free tokens left");
require(balanceOf(_msgSender()) == 0, "You already have a mooncake. Enjoy it!");
// Effects
numFreeMints += 1;
_safeMint(_msgSender(), total, "");
}
|
0.8.4
|
/**
* @dev Return detail information about an owner's token (tokenId, current level, potential level, uri)
*/
|
function tokenDetailOfOwnerByIndex(address _owner, uint256 index)
public
view
returns (
uint256,
uint256,
uint256,
string memory
)
{
uint256 tokenId = tokenOfOwnerByIndex(_owner, index);
uint256 tokenLevel = tokenLevels[tokenId];
uint256 tokenTransferCount = tokenTransferCounts[tokenId];
string memory uri = tokenURI(tokenId);
return (tokenId, tokenLevel, tokenTransferCount, uri);
}
|
0.8.4
|
/**
* @dev Reserve tokens and gift tokens
*/
|
function deployerMintMultiple(address[] calldata recipients) external payable onlyDeployer {
require(!contractSealed, "Contract sealed");
uint256 total = totalSupply();
require(total + recipients.length <= maxNftSupply, "Sold out");
for (uint256 i = 0; i < recipients.length; i++) {
require(recipients[i] != address(0), "Can't mint to null address");
_safeMint(recipients[i], total + i);
}
}
|
0.8.4
|
/**
* @dev Deployer parameters
*/
|
function deployerSetParam(uint256 key, uint256 value) external onlyDeployer {
require(!contractSealed, "Contract sealed");
if (key == 0) {
SALES_START_TIMESTAMP = value;
} else if (key == 1) {
CLAIM_START_TIMESTAMP = value;
} else if (key == 2) {
MINT_FEE = value;
} else if (key == 3) {
maxNftSupply = value;
} else if (key == 4) {
maxFreeMints = value;
} else {
revert();
}
}
|
0.8.4
|
/**
* @dev Mints multiple tokens to an address and mints unminted maco cash.
* @dev Called by server
* @param _tokenIds array of ids of the token
* @param _to address of the future owner of the token
*/
|
function mintMultipleTo(uint256[] memory _tokenIds, address _to, uint256 _notMinted) public onlyL2Account {
for(uint i = 0; i < _tokenIds.length;i++) {
require(!_exists(_tokenIds[i]), "token_exists");
_mint(_to, _tokenIds[i]);
}
mintedSupply = mintedSupply + uint32(_tokenIds.length);
if(_notMinted > 0) {
maco.mintFromCash(_notMinted);
}
}
|
0.5.17
|
/**
* @dev Deposits token on contract to use off-chain
* @param _tokenId address of the future owner of the token
*/
|
function deposit(uint256 _tokenId) public {
require(ownerOf(_tokenId) == msg.sender, "deposit_not_by_owner");
// would be nicer to have address(this) instead of owner, but then
// for the release, the owner can not be approved by the contract
transferFrom(msg.sender, address(this), _tokenId);
// Solution with calling own contract call to change msg.sender...
Holomate myself = Holomate(address(this));
myself.approve(owner(), _tokenId);
//emit NFTEvent(3, _tokenId, msg.sender, 0);
dao.depositNFT(_tokenId, msg.sender);
}
|
0.5.17
|
/**
* @dev Mint SNGT tokens and aproves the passed address to spend the minted amount of tokens
* No more than 500,000,000 SNGT can be minted
* @param _target The address to which new tokens will be minted
* @param _mintedAmount The amout of tokens to be minted
* @param _spender The address which will spend minted funds
*/
|
function mintTokensWithApproval(address _target, uint256 _mintedAmount, address _spender) public onlyOwner returns (bool success){
require(_mintedAmount <= _unmintedTokens);
balances[_target] = balances[_target].add(_mintedAmount);
_unmintedTokens = _unmintedTokens.sub(_mintedAmount);
totalSupply = totalSupply.add(_mintedAmount);
allowed[_target][_spender] = allowed[_target][_spender].add(_mintedAmount);
emit Mint(_target, _mintedAmount);
return true;
}
|
0.4.24
|
/**
* @dev Emits events to release a token from off-chain storage into the blockchain
* @param _tokenId address of the future owner of the token
*/
|
function pickUp(uint256 _tokenId) public payable {
require(tx.gasprice * gasToPickup <= msg.value, "min_price");
// pay owner the gas fee it needs to call release
address payable payowner = address(uint160(owner()));
require(payowner.send( msg.value ), "fees_to_owner");
//→ emit event for off-chain listener
//emit NFTEvent(2, _tokenId, msg.sender, msg.value);
dao.pickUpNFT(_tokenId, msg.sender, msg.value);
}
|
0.5.17
|
/**
* @dev transfer token to a contract address with additional data if the recipient is a contact.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @param _data The extra data to be passed to the receiving contract.
*/
|
function transferAndCall(address _to, uint _value, bytes calldata _data)
public
override
returns (bool success)
{
super.transfer(_to, _value);
emit TransferWithData(msg.sender, _to, _value, _data);
if (isContract(_to)) {
contractFallback(_to, _value, _data);
}
return true;
}
|
0.8.4
|
/**
* @dev See {IERC20Permit-permit}.
*/
|
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
|
0.8.4
|
/**
* @notice function for minting piece
* @dev requires owner
* @param _merkleProof is the proof for whitelist
*/
|
function mint(bytes32[] calldata _merkleProof) public {
require(mintStatus, "Error: mint not open");
require (availableTokenSupply > 0, "Error: no more tokens left to mint");
require(!hasMinted[msg.sender], "Error: already minted");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, merkleRoot, leaf), "Error: not on whitelist");
_mint(msg.sender, 0, 1, "");
hasMinted[msg.sender] = true;
availableTokenSupply -= 1;
}
|
0.8.9
|
/**
* @notice function for minting to address
* @dev only owner
* @dev only used as backup
* @param _address is the address to mint to
* @param _num is the number to mint
*/
|
function adminMint(address _address, uint256 _num) public onlyOwner {
require (availableTokenSupply > 0, "Error: no more tokens left to mint");
require(_address != address(0), "Error: trying to mint to zero address");
for (uint256 i = 0; i < _num; i++) {
_mint(_address, 0, 1, "");
}
availableTokenSupply -= _num;
}
|
0.8.9
|
// Extend lock Duration
|
function extendLockDuration(uint256 _id, uint256 _unlockTime) external {
require(!lockedToken[_id].withdrawn, 'TokenLock: withdrawable is false');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'TokenLock: not accessible');
// set new unlock time
lockedToken[_id].unlockTime = lockedToken[_id].unlockTime.add(_unlockTime.mul(1 days));
lockedToken[_id].blockTime = block.timestamp;
emit ExtendLockDuration(_id, _unlockTime);
}
|
0.6.6
|
// withdraw token
|
function withdrawToken(uint256 _id) external {
require(block.timestamp >= lockedToken[_id].unlockTime, 'TokenLock: not expired yet');
require(msg.sender == lockedToken[_id].withdrawalAddress, 'TokenLock: not accessible');
require(!lockedToken[_id].withdrawn, 'TokenLock: withdrawable not accepct');
// transfer tokens to wallet address
IERC20(lockedToken[_id].tokenAddress).safeTransfer(msg.sender, lockedToken[_id].tokenAmount);
Items memory lockItem = lockedToken[_id];
lockItem.withdrawn = true;
lockItem.blockTime = block.timestamp;
lockedToken[_id] = lockItem;
// update balance of addresss
walletTokenBalance[lockedToken[_id].tokenAddress][msg.sender] = 0;
emit WithdrawToken(msg.sender, lockedToken[_id].tokenAmount);
}
|
0.6.6
|
// swapAndLiquify takes the balance to be liquified and make sure it is equally distributed
// in BNB and Harold
|
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
// 1/2 balance is sent to the marketing wallet, 1/2 is added to the liquidity pool
uint256 marketingTokenBalance = contractTokenBalance.div(2);
uint256 liquidityTokenBalance = contractTokenBalance.sub(marketingTokenBalance);
uint256 tokenBalanceToLiquifyAsBNB = liquidityTokenBalance.div(2);
uint256 tokenBalanceToLiquify = liquidityTokenBalance.sub(tokenBalanceToLiquifyAsBNB);
uint256 initialBalance = address(this).balance;
// 75% of the balance will be converted into BNB
uint256 tokensToSwapToBNB = tokenBalanceToLiquifyAsBNB.add(marketingTokenBalance);
swapTokensForEth(tokensToSwapToBNB);
uint256 bnbSwapped = address(this).balance.sub(initialBalance);
uint256 bnbToLiquify = bnbSwapped.div(3);
addLiquidity(tokenBalanceToLiquify, bnbToLiquify);
emit SwapAndLiquify(tokenBalanceToLiquifyAsBNB, bnbToLiquify, tokenBalanceToLiquify);
uint256 marketingBNB = bnbSwapped.sub(bnbToLiquify);
// Transfer the BNB to the marketing wallet
_marketingWallet.transfer(marketingBNB);
emit ToMarketing(marketingBNB);
}
|
0.8.7
|
// Get deposit detail
|
function getDepositDetails(uint256 _id) public view returns (address _tokenAddress, address _withdrawalAddress, uint256 _tokenAmount, uint256 _unlockTime, bool _withdrawn, uint256 _blockTime, uint256 _lockedTime) {
return (
lockedToken[_id].tokenAddress,
lockedToken[_id].withdrawalAddress,
lockedToken[_id].tokenAmount,
lockedToken[_id].unlockTime,
lockedToken[_id].withdrawn,
lockedToken[_id].blockTime,
lockedToken[_id].lockedTime
);
}
|
0.6.6
|
//Set pool rewards
|
function ownerSetPoolRewards(uint256 _rewardAmount) external onlyOwner {
require(poolStartTime == 0, "Pool rewards already set");
require(_rewardAmount > 0, "Cannot create pool with zero amount");
//set total rewards value
totalRewards = _rewardAmount;
poolStartTime = now;
poolEndTime = now + poolDuration;
//transfer tokens to contract
rewardToken.transferFrom(msg.sender, this, _rewardAmount);
emit OwnerSetReward(_rewardAmount);
}
|
0.4.25
|
//Stake function for users to stake SWAP token
|
function stake(uint256 amount) external {
require(amount > 0, "Cannot stake 0");
require(now < poolEndTime, "Staking pool is closed"); //staking pool is closed for staking
//add value in staking
userTotalStaking[msg.sender].totalStaking = userTotalStaking[msg.sender].totalStaking.add(amount);
//add new stake
Stake memory newStake = Stake(amount, now, 0);
userStaking[msg.sender].push(newStake);
//add to total staked
totalStaked = totalStaked.add(amount);
tswap.transferFrom(msg.sender, this, amount);
emit Staked(msg.sender, amount);
}
|
0.4.25
|
//compute rewards
|
function computeNewReward(uint256 _rewardAmount, uint256 _stakedAmount, uint256 _stakeTimeSec) private view returns (uint256 _reward) {
uint256 rewardPerSecond = totalRewards.mul(1 ether);
if (rewardPerSecond != 0 ) {
rewardPerSecond = rewardPerSecond.div(poolDuration);
}
if (rewardPerSecond > 0) {
uint256 rewardPerSecForEachTokenStaked = rewardPerSecond.div(totalStaked);
uint256 userRewards = rewardPerSecForEachTokenStaked.mul(_stakedAmount).mul(_stakeTimeSec);
userRewards = userRewards.div(1 ether);
return _rewardAmount.add(userRewards);
} else {
return 0;
}
}
|
0.4.25
|
//calculate your rewards
|
function calculateReward(address _userAddress) public view returns (uint256 _reward) {
// all user stakes
Stake[] storage accountStakes = userStaking[_userAddress];
// Redeem from most recent stake and go backwards in time.
uint256 rewardAmount = 0;
uint256 i = accountStakes.length;
while (i > 0) {
Stake storage userStake = accountStakes[i - 1];
uint256 stakeTimeSec;
//check if current time is more than pool ending time
if (now > poolEndTime) {
stakeTimeSec = poolEndTime.sub(userStake.stakingTime);
if(userStake.lastWithdrawTime != 0){
stakeTimeSec = poolEndTime.sub(userStake.lastWithdrawTime);
}
} else {
stakeTimeSec = now.sub(userStake.stakingTime);
if(userStake.lastWithdrawTime != 0){
stakeTimeSec = now.sub(userStake.lastWithdrawTime);
}
}
// fully redeem a past stake
rewardAmount = computeNewReward(rewardAmount, userStake.amount, stakeTimeSec);
i--;
}
return rewardAmount;
}
|
0.4.25
|
//Withdraw rewards
|
function withdrawRewardsOnly() external {
uint256 _rwdAmount = calculateReward(msg.sender);
require(_rwdAmount > 0, "You do not have enough rewards");
// 1. User Accounting
Stake[] storage accountStakes = userStaking[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 rewardAmount = 0;
uint256 i = accountStakes.length;
while (i > 0) {
Stake storage userStake = accountStakes[i - 1];
uint256 stakeTimeSec;
//check if current time is more than pool ending time
if (now > poolEndTime) {
stakeTimeSec = poolEndTime.sub(userStake.stakingTime);
if(userStake.lastWithdrawTime != 0){
stakeTimeSec = poolEndTime.sub(userStake.lastWithdrawTime);
}
} else {
stakeTimeSec = now.sub(userStake.stakingTime);
if(userStake.lastWithdrawTime != 0){
stakeTimeSec = now.sub(userStake.lastWithdrawTime);
}
}
// fully redeem a past stake
rewardAmount = computeNewReward(rewardAmount, userStake.amount, stakeTimeSec);
userStake.lastWithdrawTime = now;
i--;
}
//update user rewards info
userRewardInfo[msg.sender].totalWithdrawn = userRewardInfo[msg.sender].totalWithdrawn.add(rewardAmount);
userRewardInfo[msg.sender].lastWithdrawTime = now;
//update total rewards withdrawn
rewardsWithdrawn = rewardsWithdrawn.add(rewardAmount);
//transfer rewards
rewardToken.transfer(msg.sender, rewardAmount);
emit RewardWithdrawal(msg.sender, rewardAmount);
}
|
0.4.25
|
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE` and only admin can mint to self.
* - Supply should not exceed max allowed token supply
*/
|
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "SatoshiToken: must have minter role to mint");
require(amount + totalSupply() <= MAX_TOKEN_SUPPLY, "SatoshiToken: Supply exceeds maximum token supply");
if (to == _msgSender()) {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "SatoshiToken: must have admin role to mint to self");
}
_mint(to, amount);
}
|
0.5.16
|
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
|
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
|
0.4.24
|
/**
* @param _hashID token holder customized field, the HashFuture account ID
* @param _name token holder customized field, the name of the holder
* @param _country token holder customized field.
* @param _photoUrl token holder customized field, link to holder's photo
* @param _institute token holder customized field, institute the holder works for
* @param _occupation token holder customized field, holder's occupation in the institute he/she works in
* @param _suggestions token holder customized field, holder's suggestions for HashFuture
**/
|
function issueToken(
address _to,
string _hashID,
string _name,
string _country,
string _photoUrl,
string _institute,
string _occupation,
string _suggestions
)
public onlyOwner
{
uint256 _tokenId = allTokens.length;
IdentityInfoOfId[_tokenId] = IdentityInfo(
_hashID, _name, _country, _photoUrl,
_institute, _occupation, _suggestions
);
_mint(_to, _tokenId);
}
|
0.4.24
|
/**
* @dev Get the holder's info of a token.
* @param _tokenId id of interested token
**/
|
function getTokenInfo(uint256 _tokenId)
external view
returns (string, string, string, string, string, string, string)
{
address tokenOwner = ownerOf(_tokenId);
require(tokenOwner != address(0));
IdentityInfo storage pInfo = IdentityInfoOfId[_tokenId];
return (
pInfo.hashID,
pInfo.name,
pInfo.country,
pInfo.photoUrl,
pInfo.institute,
pInfo.occupation,
pInfo.suggestions
);
}
|
0.4.24
|
/**
* @dev Set holder's IdentityInfo of a token
* @param _tokenId id of target token.
* @param _name token holder customized field, the name of the holder
* @param _country token holder customized field.
* @param _photoUrl token holder customized field, link to holder's photo
* @param _institute token holder customized field, institute the holder works for
* @param _occupation token holder customized field, holder's occupation in the institute he/she works in
* @param _suggestions token holder customized field, holder's suggestions for HashFuture
**/
|
function setIdentityInfo(
uint256 _tokenId,
string _name,
string _country,
string _photoUrl,
string _institute,
string _occupation,
string _suggestions
)
public
onlyOwnerOf(_tokenId)
{
IdentityInfo storage pInfo = IdentityInfoOfId[_tokenId];
pInfo.name = _name;
pInfo.country = _country;
pInfo.photoUrl = _photoUrl;
pInfo.institute = _institute;
pInfo.occupation = _occupation;
pInfo.suggestions = _suggestions;
}
|
0.4.24
|
//only admin and game is not run
|
function startArgs(uint dailyInvest, uint safePool, uint gloryPool, uint staticPool, uint[] memory locks) public onlyAdmin() {
require(!isStart(), "Game Not Start Limit");
_dailyInvest = dailyInvest;
_safePool = safePool;
_gloryPool = gloryPool;
_staticPool = staticPool;
for(uint i=0; i<locks.length; i++) {
lockedRound.push(locks[i]);
}
}
|
0.5.12
|
/**
* @dev ETH to Maco Cash
*/
|
function toMacoCash(uint160 sqrtPriceLimitX96) public payable {
wrap(msg.value);
WETH.approve(macoEthUniswapPoolAddress, msg.value);
// → coinswap ETH/MACO
// 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)
*/
macoEthUniswapPool.swap(address(this), !macoEthUniswapPoolToken0IsMaco, int256(msg.value), sqrtPriceLimitX96, swapDataToBytes(SwapData(2, msg.sender)));
}
|
0.5.17
|
/**
* @dev Maco Cash to Coin: Emits event to cash out deposited Maco Cash to Maco in user's wallet
* @param _amount amount of maco 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);
if(_toEth) {
dao.cashOutEth(msg.sender, msg.value, _amount);
} else {
dao.cashOutMaco(msg.sender, msg.value, _amount);
}
}
|
0.5.17
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.