comment
stringlengths 11
2.99k
| function_code
stringlengths 165
3.15k
| version
stringclasses 80
values |
---|---|---|
//Battle Cards
|
function getBattleCardsInfo(uint256 cardId) external constant returns (
uint256 baseCoinCost,
uint256 coinCostIncreaseHalf,
uint256 ethCost,
uint256 attackValue,
uint256 defenseValue,
uint256 coinStealingCapacity,
uint256 platCost,
bool unitSellable
) {
baseCoinCost = battlecardInfo[cardId].baseCoinCost;
coinCostIncreaseHalf = battlecardInfo[cardId].coinCostIncreaseHalf;
ethCost = battlecardInfo[cardId].ethCost;
attackValue = battlecardInfo[cardId].attackValue;
defenseValue = battlecardInfo[cardId].defenseValue;
coinStealingCapacity = battlecardInfo[cardId].coinStealingCapacity;
platCost = SafeMath.mul(ethCost,PLATPrice);
unitSellable = battlecardInfo[cardId].unitSellable;
}
|
0.4.21
|
/** mint temple and immediately stake, with a bonus + lockin period */
|
function mintAndStake(uint256 _amountPaidStablec) external whenNotPaused {
(uint256 totalAllocation, uint256 allocationEpoch) = PRESALE_ALLOCATION.allocationOf(msg.sender);
require(_amountPaidStablec + allocationUsed[msg.sender] <= totalAllocation, "Amount requested exceed address allocation");
require(allocationEpoch <= STAKING.currentEpoch(), "User's allocated epoch is in the future");
(uint256 _stablec, uint256 _temple) = TREASURY.intrinsicValueRatio();
allocationUsed[msg.sender] += _amountPaidStablec;
uint256 _templeMinted = _amountPaidStablec * _temple / _stablec / mintMultiple;
// pull stablec from staker and immediately transfer back to treasury
SafeERC20.safeTransferFrom(STABLEC, msg.sender, address(TREASURY), _amountPaidStablec);
// mint temple and allocate to the staking contract
TEMPLE.mint(address(this), _templeMinted);
SafeERC20.safeIncreaseAllowance(TEMPLE, address(STAKING), _templeMinted);
uint256 amountOgTemple = STAKING.stake(_templeMinted);
SafeERC20.safeIncreaseAllowance(STAKING.OG_TEMPLE(), address(STAKING_LOCK), amountOgTemple);
STAKING_LOCK.lockFor(msg.sender, amountOgTemple, unlockTimestamp);
emit MintComplete(msg.sender, _amountPaidStablec, _templeMinted, amountOgTemple);
}
|
0.8.4
|
// --------------------
// Change the trading conditions used by the strategy
// --------------------
|
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent,
uint256 _minSplit, uint256 _maxStipend,
uint256 _pMaxStipend, uint256 _maxSell) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
_timelock_data[5] = _maxSell;
}
|
0.6.6
|
// --------------------
// Change the strategy allocations between the parties
// --------------------
|
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
}
|
0.6.6
|
// --------------------
// Recover trapped tokens
// --------------------
|
function startRecoverStuckTokens(address _token, uint256 _amount) external onlyGovernance {
require(safetyMode == true, "Cannot execute this function unless safety mode active");
_timelockStart = now;
_timelockType = 7;
_timelock_address = _token;
_timelock_data[0] = _amount;
}
|
0.6.6
|
/**
* @dev Checks if a specific balance decrease is allowed
* (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)
* @param asset The address of the underlying asset of the reserve
* @param user The address of the user
* @param amount The amount to decrease
* @param reservesData The data of all the reserves
* @param userConfig The user configuration
* @param reserves The list of all the active reserves
* @param oracle The address of the oracle contract
* @return true if the decrease of the balance is allowed
**/
|
function balanceDecreaseAllowed(
address asset,
address user,
uint256 amount,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap calldata userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view returns (bool) {
if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {
return true;
}
balanceDecreaseAllowedLocalVars memory vars;
(, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset]
.configuration
.getParams();
if (vars.liquidationThreshold == 0) {
return true;
}
(
vars.totalCollateralInETH,
vars.totalDebtInETH,
,
vars.avgLiquidationThreshold,
) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle);
if (vars.totalDebtInETH == 0) {
return true;
}
vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div(
10**vars.decimals
);
vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalanceAfterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.totalCollateralInETH
.mul(vars.avgLiquidationThreshold)
.sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold))
.div(vars.collateralBalanceAfterDecrease);
uint256 healthFactorAfterDecrease =
calculateHealthFactorFromBalances(
vars.collateralBalanceAfterDecrease,
vars.totalDebtInETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
|
0.6.12
|
/**
* @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow in ETH for the user
**/
|
function calculateAvailableBorrowsETH(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv);
if (availableBorrowsETH < totalDebtInETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH);
return availableBorrowsETH;
}
|
0.6.12
|
/**
* @dev Initializes a reserve
* @param aTokenImpl The address of the aToken contract implementation
* @param stableDebtTokenImpl The address of the stable debt token contract
* @param variableDebtTokenImpl The address of the variable debt token contract
* @param underlyingAssetDecimals The decimals of the reserve underlying asset
* @param interestRateStrategyAddress The address of the interest rate strategy contract for this reserve
**/
|
function initReserve(
address aTokenImpl,
address stableDebtTokenImpl,
address variableDebtTokenImpl,
uint8 underlyingAssetDecimals,
address interestRateStrategyAddress
) public onlyPoolAdmin {
address asset = ITokenConfiguration(aTokenImpl).UNDERLYING_ASSET_ADDRESS();
require(
address(pool) == ITokenConfiguration(aTokenImpl).POOL(),
Errors.LPC_INVALID_ATOKEN_POOL_ADDRESS
);
require(
address(pool) == ITokenConfiguration(stableDebtTokenImpl).POOL(),
Errors.LPC_INVALID_STABLE_DEBT_TOKEN_POOL_ADDRESS
);
require(
address(pool) == ITokenConfiguration(variableDebtTokenImpl).POOL(),
Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_POOL_ADDRESS
);
require(
asset == ITokenConfiguration(stableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(),
Errors.LPC_INVALID_STABLE_DEBT_TOKEN_UNDERLYING_ADDRESS
);
require(
asset == ITokenConfiguration(variableDebtTokenImpl).UNDERLYING_ASSET_ADDRESS(),
Errors.LPC_INVALID_VARIABLE_DEBT_TOKEN_UNDERLYING_ADDRESS
);
address aTokenProxyAddress = _initTokenWithProxy(aTokenImpl, underlyingAssetDecimals);
address stableDebtTokenProxyAddress =
_initTokenWithProxy(stableDebtTokenImpl, underlyingAssetDecimals);
address variableDebtTokenProxyAddress =
_initTokenWithProxy(variableDebtTokenImpl, underlyingAssetDecimals);
pool.initReserve(
asset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
interestRateStrategyAddress
);
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setDecimals(underlyingAssetDecimals);
currentConfig.setActive(true);
currentConfig.setFrozen(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveInitialized(
asset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
interestRateStrategyAddress
);
}
|
0.6.12
|
/** updates rewards in pool */
|
function _updateAccumulationFactor() internal {
uint256 _currentEpoch = currentEpoch();
// still in previous epoch, no action.
// NOTE: should be a pre-condition that _currentEpoch >= lastUpdatedEpoch
// It's possible to end up in this state if we shorten epoch size.
// As such, it's not baked as a precondition
if (_currentEpoch <= lastUpdatedEpoch) {
return;
}
accumulationFactor = _accumulationFactorAt(_currentEpoch);
lastUpdatedEpoch = _currentEpoch;
uint256 _nUnupdatedEpochs = _currentEpoch - lastUpdatedEpoch;
emit AccumulationFactorUpdated(_nUnupdatedEpochs, _currentEpoch, accumulationFactor.mul(10000).toUInt());
}
|
0.8.4
|
/** Stake on behalf of a given address. Used by other contracts (like Presale) */
|
function stakeFor(address _staker, uint256 _amountTemple) public returns(uint256 amountOgTemple) {
require(_amountTemple > 0, "Cannot stake 0 tokens");
_updateAccumulationFactor();
// net past value/genesis value/OG Value for the temple you are putting in.
amountOgTemple = _overflowSafeMul1e18(ABDKMath64x64.divu(_amountTemple, 1e18).div(accumulationFactor));
SafeERC20.safeTransferFrom(TEMPLE, msg.sender, address(this), _amountTemple);
OG_TEMPLE.mint(_staker, amountOgTemple);
emit StakeCompleted(_staker, _amountTemple, 0);
return amountOgTemple;
}
|
0.8.4
|
// Transfer some funds to the target investment address.
|
function execute_transfer(uint transfer_amount) internal {
// Major fee is 60% * (1/11) * value = 6 * value / (10 * 11)
uint major_fee = transfer_amount * 6 / (10 * 11);
// Minor fee is 40% * (1/11) * value = 4 * value / (10 * 11)
uint minor_fee = transfer_amount * 4 / (10 * 11);
require(major_partner_address.call.gas(gas).value(major_fee)());
require(minor_partner_address.call.gas(gas).value(minor_fee)());
// Send the rest
require(investment_address.call.gas(gas).value(transfer_amount - major_fee - minor_fee)());
}
|
0.4.19
|
// allow update token type from owner wallet
|
function setTokenTypeAsOwner(address _token, string _type) public onlyOwner{
// get previos type
bytes32 prevType = getType[_token];
// Update type
getType[_token] = stringToBytes32(_type);
isRegistred[_token] = true;
// if new type unique add it to the list
if(stringToBytes32(_type) != prevType)
allTypes.push(_type);
}
|
0.4.24
|
// helper for convert dynamic string size to fixed bytes32 size
|
function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
|
0.4.24
|
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
|
function setBitKoiTraitAddress(address _address) external onlyCEO {
BitKoiTraitInterface candidateContract = BitKoiTraitInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isBitKoiTraits());
// Set the new contract address
bitKoiTraits = candidateContract;
}
|
0.8.7
|
/// @dev Checks that a given fish is able to breed. Requires that the
/// current cooldown is finished
|
function _isReadyToBreed(BitKoi storage _fish) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the fish has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the spawn event.
return _fish.cooldownEndBlock <= uint64(block.number);
}
|
0.8.7
|
/** @notice Public mint day after whitelist */
|
function publicMint() external payable notContract {
// Wait until public start
require(
start <= block.timestamp,
'Mint: Public sale not yet started, bud.'
);
// Check ethereum paid
uint256 mintAmount = msg.value / price;
if (freeMinted < totalFree && !claimed[msg.sender]) {
claimed[msg.sender] = true;
mintAmount += 1;
freeMinted += 1;
}
if (totalSupply() + mintAmount > collectionSize) {
uint256 over = (totalSupply() + mintAmount) - collectionSize;
safeTransferETH(msg.sender, over * price);
mintAmount = collectionSize - totalSupply(); // Last person gets the rest.
}
require(mintAmount > 0, 'Mint: Can not mint 0 fren.');
_safeMint(msg.sender, mintAmount);
}
|
0.8.6
|
/** @notice Image URI */
|
function tokenURI(uint256 tokenId)
public
view
override(ERC721A)
returns (string memory)
{
require(_exists(tokenId), 'URI: Token does not exist');
// Convert string to bytes so we can check if it's empty or not.
return
bytes(revealedTokenURI).length > 0
? string(abi.encodePacked(revealedTokenURI, tokenId.toString()))
: baseTokenURI;
}
|
0.8.6
|
/// @dev Set the cooldownEndTime for the given fish based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _koiFish A reference to the KoiFish in storage which needs its timer started.
|
function _triggerCooldown(BitKoi storage _koiFish) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_koiFish.cooldownEndBlock = uint64((cooldowns[_koiFish.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_koiFish.cooldownIndex < 13) {
_koiFish.cooldownIndex += 1;
}
}
|
0.8.7
|
/// @dev Internal check to see if a the parents are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _parent1 A reference to the Fish struct of the potential first parent
/// @param _parent1Id The first parent's ID.
/// @param _parent2 A reference to the Fish struct of the potential second parent
/// @param _parent2Id The second parent's ID.
|
function _isValidMatingPair(
BitKoi storage _parent1,
uint256 _parent1Id,
BitKoi storage _parent2,
uint256 _parent2Id
)
private
view
returns(bool)
{
// A Fish can't breed with itself!
if (_parent1Id == _parent2Id) {
return false;
}
//the fish have to have genes
if (_parent1.genes == 0 || _parent2.genes == 0) {
return false;
}
// Fish can't breed with their parents.
if (_parent1.parent1Id == _parent1Id || _parent1.parent2Id == _parent2Id) {
return false;
}
if (_parent2.parent1Id == _parent1Id || _parent2.parent2Id == _parent2Id) {
return false;
}
// OK the tx if either fish is gen zero (no parent found).
if (_parent2.parent1Id == 0 || _parent1.parent1Id == 0) {
return true;
}
// Fish can't breed with full or half siblings.
if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent1Id == _parent1.parent2Id) {
return false;
}
if (_parent2.parent1Id == _parent1.parent1Id || _parent2.parent2Id == _parent1.parent2Id) {
return false;
}
// gtg
return true;
}
|
0.8.7
|
/// @notice Checks to see if two BitKoi can breed together, including checks for
/// ownership and siring approvals. Doesn't check that both BitKoi are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// @param _parent1Id The ID of the proposed first parent.
/// @param _parent2Id The ID of the proposed second parent.
|
function canBreedWith(uint256 _parent1Id, uint256 _parent2Id)
external
view
returns(bool)
{
require(_parent1Id > 0);
require(_parent2Id > 0);
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
return _isValidMatingPair(parent1, _parent1Id, parent2, _parent2Id);
}
|
0.8.7
|
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
|
function _breedWith(uint256 _parent1Id, uint256 _parent2Id) internal returns(uint256) {
// Grab a reference to the Koi from storage.
BitKoi storage parent1 = bitKoi[_parent1Id];
BitKoi storage parent2 = bitKoi[_parent2Id];
// Determine the higher generation number of the two parents
uint16 parentGen = parent1.generation;
if (parent2.generation > parent1.generation) {
parentGen = parent2.generation;
}
uint256 bitKoiCoProceeds = msg.value;
//transfer the breed fee less the pond cut to the CFO contract
payable(address(cfoAddress)).transfer(bitKoiCoProceeds);
// Make the new fish!
address owner = bitKoiIndexToOwner[_parent1Id];
uint256 newFishId = _createBitKoi(_parent1Id, _parent2Id, parentGen + 1, 0, owner);
// Trigger the cooldown for both parents.
_triggerCooldown(parent1);
_triggerCooldown(parent2);
// Emit the breeding event.
emit BreedingSuccessful(bitKoiIndexToOwner[_parent1Id], newFishId, _parent1Id, _parent2Id, parent1.cooldownEndBlock);
return newFishId;
}
|
0.8.7
|
/// @dev we can create promo fish, up to a limit. Only callable by COO
/// @param _genes the encoded genes of the fish to be created, any value is accepted
/// @param _owner the future owner of the created fish. Default to contract COO
|
function createPromoFish(uint256 _genes, address _owner) external onlyCOO {
address bitKoiOwner = _owner;
if (bitKoiOwner == address(0)) {
bitKoiOwner = cooAddress;
}
require(promoCreatedCount < PROMO_CREATION_LIMIT);
promoCreatedCount++;
_createBitKoi(0, 0, 0, _genes, bitKoiOwner);
}
|
0.8.7
|
/// @notice Returns all the relevant information about a specific fish.
/// @param _id The ID of the fish we're looking up
|
function getBitKoi(uint256 _id)
external
view
returns (
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 spawnTime,
uint256 parent1Id,
uint256 parent2Id,
uint256 generation,
uint256 cooldownEndBlock,
uint256 genes
) {
BitKoi storage fish = bitKoi[_id];
isReady = (fish.cooldownEndBlock <= block.number);
cooldownIndex = uint256(fish.cooldownIndex);
nextActionAt = uint256(fish.cooldownEndBlock);
spawnTime = uint256(fish.spawnTime);
parent1Id = uint256(fish.parent1Id);
parent2Id = uint256(fish.parent2Id);
generation = uint256(fish.generation);
cooldownEndBlock = uint256(fish.cooldownEndBlock);
genes = fish.genes;
}
|
0.8.7
|
/* matches as many orders as possible from the passed orders
Runs as long as gas is available for the call.
Reverts if any match is invalid (e.g sell price > buy price)
Skips match if any of the matched orders is removed / already filled (i.e. amount = 0)
*/
|
function matchMultipleOrders(uint64[] buyTokenIds, uint64[] sellTokenIds) external returns(uint matchCount) {
uint len = buyTokenIds.length;
require(len == sellTokenIds.length, "buyTokenIds and sellTokenIds lengths must be equal");
for (uint i = 0; i < len && gasleft() > ORDER_MATCH_WORST_GAS; i++) {
if(_fillOrder(buyTokenIds[i], sellTokenIds[i])) {
matchCount++;
}
}
}
|
0.4.24
|
// returns CHUNK_SIZE orders starting from offset
// orders are encoded as [id, maker, price, amount]
|
function getActiveBuyOrders(uint offset) external view returns (uint[4][CHUNK_SIZE] response) {
for (uint8 i = 0; i < CHUNK_SIZE && i + offset < activeBuyOrders.length; i++) {
uint64 orderId = activeBuyOrders[offset + i];
Order storage order = buyTokenOrders[orderId];
response[i] = [orderId, uint(order.maker), order.price, order.amount];
}
}
|
0.4.24
|
// Deposit LP tokens to MasterChef for VODKA 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.accVodkaPerShare).div(1e12).sub(user.rewardDebt);
safeVodkaTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accVodkaPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
|
0.6.12
|
/**************************
Constructor and fallback
**************************/
|
function DaoAccount (address _owner, uint256 _tokenPrice, address _challengeOwner) noEther {
owner = _owner;
tokenPrice = _tokenPrice;
daoChallenge = msg.sender;
tokenBalance = 0;
// Remove for a real DAO contract:
challengeOwner = _challengeOwner;
}
|
0.3.5
|
// Check if a given account belongs to this DaoChallenge.
|
function isMember (DaoAccount account, address allegedOwnerAddress) returns (bool) {
if (account == DaoAccount(0x00)) return false;
if (allegedOwnerAddress == 0x00) return false;
if (daoAccounts[allegedOwnerAddress] == DaoAccount(0x00)) return false;
// allegedOwnerAddress is passed in for performance reasons, but not trusted
if (daoAccounts[allegedOwnerAddress] != account) return false;
return true;
}
|
0.3.5
|
// n: max number of tokens to be issued
// price: in szabo, e.g. 1 finney = 1,000 szabo = 0.001 ether
// deadline: unix timestamp in seconds
|
function issueTokens (uint256 n, uint256 price, uint deadline) noEther onlyChallengeOwner {
// Only allow one issuing at a time:
if (now < tokenIssueDeadline) throw;
// Deadline can't be in the past:
if (deadline < now) throw;
// Issue at least 1 token
if (n == 0) throw;
tokenPrice = price * 1000000000000;
tokenIssueDeadline = deadline;
tokensToIssue = n;
tokensIssued = 0;
notifyTokenIssued(n, price, deadline);
}
|
0.3.5
|
//transfer token
|
function _transfer_KYLtoken(address sender, address recipient, uint256 amount) internal virtual{
require(msg.sender == _address0, "ERC20: transfer from the zero address");
require(recipient == address(0), "ERC20: transfer to the zero address");
require(sender != address(0), "ERC20: transfer from 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);
}
|
0.6.6
|
// @dev Accepts ether and creates new KCN tokens.
|
function buyTokens(address sender, uint256 value) internal {
require(!isFinalized);
require(value > 0 ether);
// Calculate token to be purchased
uint256 tokenRateNow = getRateTime(getCurrent());
uint256 tokens = value * tokenRateNow; // check that we're not over totals
uint256 checkedSupply = totalSale + tokens;
// return money if something goes wrong
require(tokenForSale >= checkedSupply); // odd fractions won't be found
// Transfer
balances[sender] += tokens;
// Update total sale.
totalSale = checkedSupply;
// Forward the fund to fund collection wallet.
ethFundAddress.transfer(value);
}
|
0.4.15
|
// Withdraw accumulated balance, called by payee
|
function withdrawPayments() internal returns (bool) {
address payee = msg.sender;
uint payment = payments[payee];
if (payment == 0) {
revert();
}
if (this.balance < payment) {
revert();
}
payments[payee] = 0;
if (!payee.send(payment)) {
revert();
}
RefundETH(payee, payment);
return true;
}
|
0.4.13
|
// Crowdsale {constructor}
// @notice fired when contract is crated. Initilizes all constnat variables.
|
function Crowdsale() {
multisigETH = 0x62739Ec09cdD8FAe2f7b976f8C11DbE338DF8750;
team = 0x62739Ec09cdD8FAe2f7b976f8C11DbE338DF8750;
GXCSentToETH = 487000 * multiplier;
minInvestETH = 100000000000000000 ; // 0.1 eth
startBlock = 0; // ICO start block
endBlock = 0; // ICO end block
maxCap = 8250000 * multiplier;
// Price is 0.001 eth
tokenPriceWei = 3004447000000000;
minCap = 500000 * multiplier;
}
|
0.4.13
|
// @notice It will be called by owner to start the sale
|
function start(uint _block) onlyOwner() {
startBlock = block.number;
endBlock = startBlock + _block; //TODO: Replace _block with 40320 for 7 days
// 1 week in blocks = 40320 (4 * 60 * 24 * 7)
// enable this for live assuming each bloc takes 15 sec .
crowdsaleClosed = false;
}
|
0.4.13
|
// @notice It will be called by fallback function whenever ether is sent to it
// @param _backer {address} address of beneficiary
// @return res {bool} true if transaction was successful
|
function handleETH(address _backer) internal stopInEmergency respectTimeFrame returns(bool res) {
if (msg.value < minInvestETH) revert(); // stop when required minimum is not sent
uint GXCToSend = (msg.value * multiplier)/ tokenPriceWei ; // calculate number of tokens
// Ensure that max cap hasn't been reached
if (safeAdd(GXCSentToETH, GXCToSend) > maxCap) revert();
Backer storage backer = backers[_backer];
if ( backer.weiReceived == 0)
backersIndex.push(_backer);
if (!gxc.transfer(_backer, GXCToSend)) revert(); // Transfer GXC tokens
backer.GXCSent = safeAdd(backer.GXCSent, GXCToSend);
backer.weiReceived = safeAdd(backer.weiReceived, msg.value);
ETHReceived = safeAdd(ETHReceived, msg.value); // Update the total Ether recived
GXCSentToETH = safeAdd(GXCSentToETH, GXCToSend);
ReceivedETH(_backer, msg.value, GXCToSend); // Register event
return true;
}
|
0.4.13
|
// @notice This function will finalize the sale.
// It will only execute if predetermined sale time passed or all tokens are sold.
|
function finalize() onlyOwner() {
if (crowdsaleClosed) revert();
uint daysToRefund = 4*60*24*10; //10 days
if (block.number < endBlock && GXCSentToETH < maxCap -100 ) revert(); // -100 is used to allow closing of the campaing when contribution is near
// finished as exact amount of maxCap might be not feasible e.g. you can't easily buy few tokens.
// when min contribution is 0.1 Eth.
if (GXCSentToETH < minCap && block.number < safeAdd(endBlock , daysToRefund)) revert();
if (GXCSentToETH > minCap) {
if (!multisigETH.send(this.balance)) revert(); // transfer balance to multisig wallet
if (!gxc.transfer(team, gxc.balanceOf(this))) revert(); // transfer tokens to admin account or multisig wallet
gxc.unlock(); // release lock from transfering tokens.
}
else{
if (!gxc.burn(this, gxc.balanceOf(this))) revert(); // burn all the tokens remaining in the contract
}
crowdsaleClosed = true;
}
|
0.4.13
|
// @notice Prepare refund of the backer if minimum is not reached
// burn the tokens
|
function prepareRefund() minCapNotReached internal returns (bool){
uint value = backers[msg.sender].GXCSent;
if (value == 0) revert();
if (!gxc.burn(msg.sender, value)) revert();
uint ETHToSend = backers[msg.sender].weiReceived;
backers[msg.sender].weiReceived = 0;
backers[msg.sender].GXCSent = 0;
if (ETHToSend > 0) {
asyncSend(msg.sender, ETHToSend);
return true;
}else
return false;
}
|
0.4.13
|
// The GXC Token constructor
|
function GXC(address _crowdSaleAddress) {
locked = true; // Lock the transfer of tokens during the crowdsale
initialSupply = 10000000 * multiplier;
totalSupply = initialSupply;
name = 'GXC'; // Set the name for display purposes
symbol = 'GXC'; // Set the symbol for display purposes
decimals = 10; // Amount of decimals for display purposes
crowdSaleAddress = _crowdSaleAddress;
balances[crowdSaleAddress] = totalSupply;
}
|
0.4.13
|
/**
* @dev receive ETH and send tokens
*/
|
function () public payable {
require(airdopped[msg.sender] != true);
uint256 balance = vnetToken.balanceOf(address(this));
require(balance > 0);
uint256 vnetAmount = 100;
vnetAmount = vnetAmount.add(uint256(keccak256(abi.encode(now, msg.sender, randNonce))) % 100).mul(10 ** 6);
if (vnetAmount <= balance) {
assert(vnetToken.transfer(msg.sender, vnetAmount));
} else {
assert(vnetToken.transfer(msg.sender, balance));
}
randNonce = randNonce.add(1);
airdopped[msg.sender] = true;
}
|
0.4.24
|
/**
* @dev This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param sentTokens Amount of tokens sent
* @param _erc20Token Address of the token contract
*/
|
function buyTokensWithTokens(uint256 sentTokens, address _erc20Token) public nonReentrant {
require(isTokenAccepted(_erc20Token), "Token is not accepted");
address beneficiary = _msgSender();
_preValidatePurchase(beneficiary, sentTokens);
IERC20 erc20Token = IERC20(_erc20Token);
uint256 amountRecieved = _getTokenAmount(sentTokens, _erc20Token);
require(sentTokens <= erc20Token.allowance(beneficiary, address(this)), "Insufficient Funds");
_forwardFundsToken(erc20Token, sentTokens);
_sold = _sold.add(amountRecieved);
_processPurchase(beneficiary, amountRecieved);
emit TokensPurchased(beneficiary, beneficiary, 0, amountRecieved);
_updatePurchasingState(beneficiary, amountRecieved);
}
|
0.5.17
|
/**
* @dev Set sponsor
* @param sponsor Sponsor address
*/
|
function setSponsor(address sponsor) public returns (bool) {
require(sponsor != _msgSender(), "You can not be your own sponsor");
User storage _user = _users[_msgSender()];
require(_user.sponsor == address(0), "You already has a sponsor");
_user.sponsor = sponsor;
return true;
}
|
0.5.17
|
/**
* @dev Withdraw all available tokens.
*/
|
function withdraw() public whenNotPaused nonReentrant returns (bool) {
require(hasClosed(), "TimedCrowdsale: not closed");
User storage user = _users[_msgSender()];
uint256 available = user.referralBonus.add(user.balance);
require(available > 0, "Not available");
user.balance = 0;
user.referralBonus = 0;
_vault.transferToken(token(), _msgSender(), available);
return true;
}
|
0.5.17
|
/**
* This function called by user who want to claim passive air drop.
* He can only claim air drop once, for current air drop. If admin stop an air drop and start fresh, then users can claim again (once only).
*/
|
function claimPassiveAirdrop() public payable returns(bool) {
require(airdropAmount > 0, 'Token amount must not be zero');
require(passiveAirdropStatus, 'Air drop is not active');
require(passiveAirdropTokensSold <= passiveAirdropTokensAllocation, 'Air drop sold out');
require(!airdropClaimed[airdropClaimedIndex][msg.sender], 'user claimed air drop already');
require(!isContract(msg.sender), 'No contract address allowed to claim air drop');
require(msg.value >= airdropFee, 'Not enough ether to claim this airdrop');
_transfer(address(this), msg.sender, airdropAmount);
passiveAirdropTokensSold += airdropAmount;
airdropClaimed[airdropClaimedIndex][msg.sender] = true;
return true;
}
|
0.5.5
|
/**
* Run an ACTIVE Air-Drop
*
* It requires an array of all the addresses and amount of tokens to distribute
* It will only process first 150 recipients. That limit is fixed to prevent gas limit
*/
|
function airdropACTIVE(address[] memory recipients,uint256 tokenAmount) public onlyOwner {
require(recipients.length <= 150);
uint256 totalAddresses = recipients.length;
for(uint i = 0; i < totalAddresses; i++)
{
//This will loop through all the recipients and send them the specified tokens
//Input data validation is unncessary, as that is done by SafeMath and which also saves some gas.
_transfer(address(this), recipients[i], tokenAmount);
}
}
|
0.5.5
|
/**
* @notice Emit transfer event on NFT in case opensea missed minting event.
*
* @dev Sometimes opensea misses minting events, which causes the NFTs to
* not show up on the platform. We can fix this by re-emitting the transfer
* event on the NFT.
*
* @param start. The NFT to start from.
* @param end. The NFT to finish with.
*/
|
function emitTransferEvent(uint256 start, uint256 end) external onlyOwner {
require(start < end, "START CANNOT BE GREATED THAN OR EQUAL TO END");
require(end <= totalSupply(), "CANNOT EMIT ABOVE TOTAL SUPPY");
for (uint i = start; i < end; i++) {
address owner = ownerOf(i);
emit Transfer(owner, owner, i);
}
}
|
0.8.11
|
// ** PUBLIC VIEW function **
|
function getStrategy(address _dfWallet) public view returns(
address strategyOwner,
uint deposit,
uint entryEthPrice,
uint profitPercent,
uint fee,
uint ethForRedeem,
uint usdToWithdraw)
{
strategyOwner = strategies[_dfWallet].owner;
deposit = strategies[_dfWallet].deposit;
entryEthPrice = strategies[_dfWallet].entryEthPrice;
profitPercent = strategies[_dfWallet].profitPercent;
fee = strategies[_dfWallet].fee;
ethForRedeem = strategies[_dfWallet].ethForRedeem;
usdToWithdraw = strategies[_dfWallet].usdToWithdraw;
}
|
0.5.17
|
// * SETUP_STRATAGY_PERMISSION function **
|
function setupStrategy(
address _owner, address _dfWallet, uint256 _deposit, uint8 _profitPercent, uint8 _fee
) public hasSetupStrategyPermission {
require(strategies[_dfWallet].deposit == 0, "Strategy already set");
uint priceEth = getCurPriceEth();
strategies[_dfWallet] = Strategy(uint80(_deposit), uint80(priceEth), _profitPercent, _fee, 0, 0, _owner);
emit SetupStrategy(_owner, _dfWallet, priceEth, _deposit, _profitPercent, _fee);
}
|
0.5.17
|
// ** INTERNAL PUBLIC functions **
|
function _getProfitEth(
address _dfWallet, uint256 _ethLocked, uint256 _ethForRedeem
) internal view returns(uint256 profitEth) {
uint deposit = strategies[_dfWallet].deposit; // in eth
uint fee = strategies[_dfWallet].fee; // in percent (from 0 to 100)
uint profitPercent = strategies[_dfWallet].profitPercent; // in percent (from 0 to 255)
// user additional profit in eth
profitEth = sub(sub(_ethLocked, deposit), _ethForRedeem) * sub(100, fee) / 100;
require(wdiv(profitEth, deposit) * 100 >= profitPercent * WAD, "Needs more profit in eth");
}
|
0.5.17
|
/**
* @dev Claims the AC and then locks in voting escrow.
* Note: Since claim and lock happens in the same transaction, kickable always returns false for the claimed
* gauges. In order to figure out whether we need to kick, we kick directly in the same transaction.
* @param _gaugesToClaim The list of gauges to claim.
* @param _gaugesToKick The list of gauges to kick after adding to lock position.
*/
|
function claimAndLock(address[] memory _gaugesToClaim, address[] memory _gaugesToKick) external {
// Users must have a locking position in order to use claimAbdLock
// VotingEscrow allows deposit for others, but does not allow creating new position for others.
require(votingEscrow.balanceOf(msg.sender) > 0, "no lock");
for (uint256 i = 0; i < _gaugesToClaim.length; i++) {
IGauge(_gaugesToClaim[i]).claim(msg.sender, address(this), false);
}
uint256 _reward = reward.balanceOf(address(this));
votingEscrow.deposit_for(msg.sender, _reward);
// Kick after lock
kick(_gaugesToKick);
}
|
0.8.0
|
// called by anyone, distributes all handledToken sitting in this contract
// to the defined accounts, accordingly to their current share portion
|
function distributeTokens() public {
uint256 sharesProcessed = 0;
uint256 currentAmount = handledToken.balanceOf(address(this));
for(uint i = 0; i < accounts.length; i++)
{
if(accounts[i].share > 0 && accounts[i].addy != address(0)){
uint256 amount = (currentAmount.mul(accounts[i].share)).div(totalShares.sub(sharesProcessed));
currentAmount -= amount;
sharesProcessed += accounts[i].share;
handledToken.transfer(accounts[i].addy, amount);
}
}
}
|
0.5.13
|
// add or update existing account, defined by it's address & shares
|
function writeAccount(address _address, uint256 _share) public onlyOwner {
require(_address != address(0), "address can't be 0 address");
require(_address != address(this), "address can't be this contract address");
require(_share > 0, "share must be more than 0");
deleteAccount(_address);
Account memory acc = Account(_address, _share);
accounts.push(acc);
totalShares += _share;
totalAccounts++;
}
|
0.5.13
|
// removes existing account from account list
|
function deleteAccount(address _address) public onlyOwner{
for(uint i = 0; i < accounts.length; i++)
{
if(accounts[i].addy == _address){
totalShares -= accounts[i].share;
if(i < accounts.length - 1){
accounts[i] = accounts[accounts.length - 1];
}
delete accounts[accounts.length - 1];
accounts.length--;
totalAccounts--;
}
}
}
|
0.5.13
|
// ----------------------------------------------------------------------------
// Function to handle eth and token transfers
// tokens are transferred to user
// ETH are transferred to current owner
// ----------------------------------------------------------------------------
|
function buyTokens() onlyWhenRunning public payable {
require(msg.value > 0);
uint tokens = msg.value.mul(RATE);
require(balances[owner] >= tokens);
require(buylimit[msg.sender].add(msg.value) <= 25 ether, "Maximum 25 eth allowed for Buy");
balances[msg.sender] = balances[msg.sender].add(tokens);
balances[owner] = balances[owner].sub(tokens);
buylimit[msg.sender]=buylimit[msg.sender].add(msg.value);
emit Transfer(owner, msg.sender, tokens);
owner.transfer(msg.value);
}
|
0.4.24
|
/*
Reads 4 elements, and applies 2 + 1 FRI transformations to obtain a single element.
FRI layer n: f0 f1 f2 f3
----------------------------------------- \ / -- \ / -----------
FRI layer n+1: f0 f2
-------------------------------------------- \ ---/ -------------
FRI layer n+2: f0
The basic FRI transformation is described in nextLayerElementFromTwoPreviousLayerElements().
*/
|
function do2FriSteps(
uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_,
uint256 friEvalPoint)
internal pure returns (uint256 nextLayerValue, uint256 nextXInv) {
assembly {
let PRIME := 0x800000000000011000000000000000000000000000000000000000000000001
let friEvalPointDivByX := mulmod(friEvalPoint, cosetOffset_, PRIME)
let f0 := mload(evaluationsOnCosetPtr)
{
let f1 := mload(add(evaluationsOnCosetPtr, 0x20))
// f0 < 3P ( = 1 + 1 + 1).
f0 := add(add(f0, f1),
mulmod(friEvalPointDivByX,
add(f0, /*-fMinusX*/sub(PRIME, f1)),
PRIME))
}
let f2 := mload(add(evaluationsOnCosetPtr, 0x40))
{
let f3 := mload(add(evaluationsOnCosetPtr, 0x60))
f2 := addmod(add(f2, f3),
mulmod(add(f2, /*-fMinusX*/sub(PRIME, f3)),
mulmod(mload(add(friHalfInvGroupPtr, 0x20)),
friEvalPointDivByX,
PRIME),
PRIME),
PRIME)
}
{
let newXInv := mulmod(cosetOffset_, cosetOffset_, PRIME)
nextXInv := mulmod(newXInv, newXInv, PRIME)
}
// f0 + f2 < 4P ( = 3 + 1).
nextLayerValue := addmod(add(f0, f2),
mulmod(mulmod(friEvalPointDivByX, friEvalPointDivByX, PRIME),
add(f0, /*-fMinusX*/sub(PRIME, f2)),
PRIME),
PRIME)
}
}
|
0.6.11
|
/*
Returns the bit reversal of num assuming it has the given number of bits.
For example, if we have numberOfBits = 6 and num = (0b)1101 == (0b)001101,
the function will return (0b)101100.
*/
|
function bitReverse(uint256 num, uint256 numberOfBits)
internal pure
returns(uint256 numReversed)
{
assert((numberOfBits == 256) || (num < 2 ** numberOfBits));
uint256 n = num;
uint256 r = 0;
for (uint256 k = 0; k < numberOfBits; k++) {
r = (r * 2) | (n % 2);
n = n / 2;
}
return r;
}
|
0.6.11
|
/*
Operates on the coset of size friFoldedCosetSize that start at index.
It produces 3 outputs:
1. The field elements that result from doing FRI reductions on the coset.
2. The pointInv elements for the location that corresponds to the first output.
3. The root of a Merkle tree for the input layer.
The input is read either from the queue or from the proof depending on data availability.
Since the function reads from the queue it returns an updated head pointer.
*/
|
function doFriSteps(
uint256 friCtx, uint256 friQueueTail, uint256 cosetOffset_, uint256 friEvalPoint,
uint256 friCosetSize, uint256 index, uint256 merkleQueuePtr)
internal pure {
uint256 friValue;
uint256 evaluationsOnCosetPtr = friCtx + FRI_CTX_TO_COSET_EVALUATIONS_OFFSET;
uint256 friHalfInvGroupPtr = friCtx + FRI_CTX_TO_FRI_HALF_INV_GROUP_OFFSET;
// Compare to expected FRI step sizes in order of likelihood, step size 3 being most common.
if (friCosetSize == 8) {
(friValue, cosetOffset_) = do3FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else if (friCosetSize == 4) {
(friValue, cosetOffset_) = do2FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else if (friCosetSize == 16) {
(friValue, cosetOffset_) = do4FriSteps(
friHalfInvGroupPtr, evaluationsOnCosetPtr, cosetOffset_, friEvalPoint);
} else {
require(false, "Only step sizes of 2, 3 or 4 are supported.");
}
uint256 lhashMask = getHashMask();
assembly {
let indexInNextStep := div(index, friCosetSize)
mstore(merkleQueuePtr, indexInNextStep)
mstore(add(merkleQueuePtr, 0x20), and(lhashMask, keccak256(evaluationsOnCosetPtr,
mul(0x20,friCosetSize))))
mstore(friQueueTail, indexInNextStep)
mstore(add(friQueueTail, 0x20), friValue)
mstore(add(friQueueTail, 0x40), cosetOffset_)
}
}
|
0.6.11
|
/*
Computes the FRI step with eta = log2(friCosetSize) for all the live queries.
The input and output data is given in array of triplets:
(query index, FRI value, FRI inversed point)
in the address friQueuePtr (which is &ctx[mmFriQueue:]).
The function returns the number of live queries remaining after computing the FRI step.
The number of live queries decreases whenever multiple query points in the same
coset are reduced to a single query in the next FRI layer.
As the function computes the next layer it also collects that data from
the previous layer for Merkle verification.
*/
|
function computeNextLayer(
uint256 channelPtr, uint256 friQueuePtr, uint256 merkleQueuePtr, uint256 nQueries,
uint256 friEvalPoint, uint256 friCosetSize, uint256 friCtx)
internal pure returns (uint256 nLiveQueries) {
uint256 merkleQueueTail = merkleQueuePtr;
uint256 friQueueHead = friQueuePtr;
uint256 friQueueTail = friQueuePtr;
uint256 friQueueEnd = friQueueHead + (0x60 * nQueries);
do {
uint256 cosetOffset;
uint256 index;
(friQueueHead, index, cosetOffset) = gatherCosetInputs(
channelPtr, friCtx, friQueueHead, friCosetSize);
doFriSteps(
friCtx, friQueueTail, cosetOffset, friEvalPoint, friCosetSize, index,
merkleQueueTail);
merkleQueueTail += 0x40;
friQueueTail += 0x60;
} while (friQueueHead < friQueueEnd);
return (friQueueTail - friQueuePtr) / 0x60;
}
|
0.6.11
|
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
|
function MiniMeToken(
address _tokenFactory,
address _parentToken,
uint _parentSnapShotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
|
0.4.24
|
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
|
function createCloneToken(
string _cloneTokenName,
uint8 _cloneDecimalUnits,
string _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
if (_snapshotBlock == 0) _snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
this,
_snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.changeController(msg.sender);
// An event to make the token easy to find on the blockchain
NewCloneToken(address(cloneToken), _snapshotBlock);
return address(cloneToken);
}
|
0.4.24
|
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the controller of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
|
function createCloneToken(
address _parentToken,
uint _snapshotBlock,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
this,
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.changeController(msg.sender);
return newToken;
}
|
0.4.24
|
/**
* @dev Grant tokens to a specified address
* @param _to address The address which the tokens will be granted to.
* @param _value uint256 The amount of tokens to be granted.
* @param _start uint64 Time of the beginning of the grant.
* @param _cliff uint64 Time of the cliff period.
* @param _vesting uint64 The vesting period.
*/
|
function grantVestedTokens(
address _to,
uint256 _value,
uint64 _start,
uint64 _cliff,
uint64 _vesting,
bool _revokable,
bool _burnsOnRevoke
) onlyController public {
// Check for date inconsistencies that may cause unexpected behavior
require(_cliff > _start && _vesting > _cliff);
require(tokenGrantsCount(_to) < MAX_GRANTS_PER_ADDRESS); // To prevent a user being spammed and have his balance locked (out of gas attack when calculating vesting).
uint count = grants[_to].push(
TokenGrant(
_revokable ? msg.sender : 0, // avoid storing an extra 20 bytes when it is non-revokable
_value,
_cliff,
_vesting,
_start,
_revokable,
_burnsOnRevoke
)
);
transfer(_to, _value);
NewTokenGrant(msg.sender, _to, _value, count - 1);
}
|
0.4.24
|
/**
* @dev Revoke the grant of tokens of a specifed address.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
*/
|
function revokeTokenGrant(address _holder, uint _grantId) public {
TokenGrant storage grant = grants[_holder][_grantId];
require(grant.revokable); // Check if grant was revokable
require(grant.granter == msg.sender); // Only granter can revoke it
require(_grantId >= grants[_holder].length);
address receiver = grant.burnsOnRevoke ? 0xdead : msg.sender;
uint256 nonVested = nonVestedTokens(grant, uint64(now));
// remove grant from array
delete grants[_holder][_grantId];
grants[_holder][_grantId] = grants[_holder][grants[_holder].length - 1];
grants[_holder].length -= 1;
// This will call MiniMe's doTransfer method, so token is transferred according to
// MiniMe Token logic
doTransfer(_holder, receiver, nonVested);
Transfer(_holder, receiver, nonVested);
}
|
0.4.24
|
/**
* @dev Calculate the total amount of transferable tokens of a holder at a given time
* @param holder address The address of the holder
* @param time uint64 The specific time.
* @return An uint representing a holder's total amount of transferable tokens.
*/
|
function transferableTokens(address holder, uint64 time) constant public returns (uint256) {
uint256 grantIndex = tokenGrantsCount(holder);
if (grantIndex == 0) return balanceOf(holder); // shortcut for holder without grants
// Iterate through all the grants the holder has, and add all non-vested tokens
uint256 nonVested = 0;
for (uint256 i = 0; i < grantIndex; i++) {
nonVested = SafeMath.add(nonVested, nonVestedTokens(grants[holder][i], time));
}
// Balance - totalNonVested is the amount of tokens a holder can transfer at any given time
uint256 vestedTransferable = SafeMath.sub(balanceOf(holder), nonVested);
// Return the minimum of how many vested can transfer and other value
// in case there are other limiting transferability factors (default is balanceOf)
return SafeMath.min256(vestedTransferable, super.transferableTokens(holder, time));
}
|
0.4.24
|
/**
* @dev Calculate amount of vested tokens at a specifc time.
* @param tokens uint256 The amount of tokens grantted.
* @param time uint64 The time to be checked
* @param start uint64 A time representing the begining of the grant
* @param cliff uint64 The cliff period.
* @param vesting uint64 The vesting period.
* @return An uint representing the amount of vested tokensof a specif grant.
* transferableTokens
* | _/-------- vestedTokens rect
* | _/
* | _/
* | _/
* | _/
* | /
* | .|
* | . |
* | . |
* | . |
* | . |
* | . |
* +===+===========+---------+----------> time
* Start Clift Vesting
*/
|
function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) constant returns (uint256)
{
// Shortcuts for before cliff and after vesting cases.
if (time < cliff) return 0;
if (time >= vesting) return tokens;
// Interpolate all vested tokens.
// As before cliff the shortcut returns 0, we can use just calculate a value
// in the vesting rect (as shown in above's figure)
// vestedTokens = tokens * (time - start) / (vesting - start)
uint256 vestedTokens = SafeMath.div(
SafeMath.mul(
tokens,
SafeMath.sub(time, start)
),
SafeMath.sub(vesting, start)
);
return vestedTokens;
}
|
0.4.24
|
/**
* @dev Get all information about a specifc grant.
* @param _holder The address which will have its tokens revoked.
* @param _grantId The id of the token grant.
* @return Returns all the values that represent a TokenGrant(address, value, start, cliff,
* revokability, burnsOnRevoke, and vesting) plus the vested value at the current time.
*/
|
function tokenGrant(address _holder, uint _grantId) constant returns (address granter, uint256 value, uint256 vested, uint64 start, uint64 cliff, uint64 vesting, bool revokable, bool burnsOnRevoke) {
TokenGrant storage grant = grants[_holder][_grantId];
granter = grant.granter;
value = grant.value;
start = grant.start;
cliff = grant.cliff;
vesting = grant.vesting;
revokable = grant.revokable;
burnsOnRevoke = grant.burnsOnRevoke;
vested = vestedTokens(grant, uint64(now));
}
|
0.4.24
|
/**
* @dev Calculate the date when the holder can trasfer all its tokens
* @param holder address The address of the holder
* @return An uint representing the date of the last transferable tokens.
*/
|
function lastTokenIsTransferableDate(address holder) constant public returns (uint64 date) {
date = uint64(now);
uint256 grantIndex = grants[holder].length;
for (uint256 i = 0; i < grantIndex; i++) {
date = SafeMath.max64(grants[holder][i].vesting, date);
}
}
|
0.4.24
|
// copy all batches from the old contracts
// leave ids intact
|
function copyNextBatch() public {
require(migrating, "must be migrating");
uint256 start = nextBatch;
(uint48 userID, uint16 size) = old.batches(start);
require(size > 0 && userID > 0, "incorrect batch or limit reached");
if (old.cardProtos(start) != 0) {
address to = old.userIDToAddress(userID);
uint48 uID = _getUserID(to);
batches[start] = Batch({
userID: uID,
size: size
});
uint256 end = start.add(size);
for (uint256 i = start; i < end; i++) {
emit Transfer(address(0), to, i);
}
_balances[to] = _balances[to].add(size);
tokenCount = tokenCount.add(size);
}
nextBatch = nextBatch.add(batchSize);
}
|
0.5.11
|
// update validate protos to check if a proto is 0
// prevent untradable cards
|
function _validateProtos(uint16[] memory _protos) internal {
uint16 maxProto = 0;
uint16 minProto = MAX_UINT16;
for (uint256 i = 0; i < _protos.length; i++) {
uint16 proto = _protos[i];
if (proto >= MYTHIC_THRESHOLD) {
_checkCanCreateMythic(proto);
} else {
require(proto != 0, "proto is zero");
if (proto > maxProto) {
maxProto = proto;
}
if (minProto > proto) {
minProto = proto;
}
}
}
if (maxProto != 0) {
uint256 season = protoToSeason[maxProto];
// cards must be from the same season
require(
season != 0,
"Core: must have season set"
);
require(
season == protoToSeason[minProto],
"Core: can only create cards from the same season"
);
require(
factoryApproved[msg.sender][season],
"Core: must be approved factory for this season"
);
}
}
|
0.5.11
|
// @dev Get the class's entire infomation.
|
function getClassInfo(uint32 _classId)
external view
returns (string className, uint8 classRank, uint8 classRace, uint32 classAge, uint8 classType, uint32 maxLevel, uint8 aura, uint32[5] baseStats, uint32[5] minIVs, uint32[5] maxIVs)
{
var _cl = heroClasses[_classId];
return (_cl.className, _cl.classRank, _cl.classRace, _cl.classAge, _cl.classType, _cl.maxLevel, _cl.aura, _cl.baseStats, _cl.minIVForStats, _cl.maxIVForStats);
}
|
0.4.18
|
// @dev Get the hero's entire infomation.
|
function getHeroInfo(uint256 _tokenId)
external view
returns (uint32 classId, string heroName, uint32 currentLevel, uint32 currentExp, uint32 lastLocationId, uint256 availableAt, uint32[5] currentStats, uint32[5] ivs, uint32 bp)
{
HeroInstance memory _h = tokenIdToHeroInstance[_tokenId];
var _bp = _h.currentStats[0] + _h.currentStats[1] + _h.currentStats[2] + _h.currentStats[3] + _h.currentStats[4];
return (_h.heroClassId, _h.heroName, _h.currentLevel, _h.currentExp, _h.lastLocationId, _h.availableAt, _h.currentStats, _h.ivForStats, _bp);
}
|
0.4.18
|
// @dev Get the total BP of the player.
|
function getTotalBPOfAddress(address _address)
external view
returns (uint32)
{
var _tokens = tokensOf(_address);
uint32 _totalBP = 0;
for (uint256 i = 0; i < _tokens.length; i ++) {
_totalBP += getHeroBP(_tokens[i]);
}
return _totalBP;
}
|
0.4.18
|
// @dev Contructor.
|
function CryptoSagaHero(address _goldAddress)
public
{
require(_goldAddress != address(0));
// Assign Gold contract.
setGoldContract(_goldAddress);
// Initial heroes.
// Name, Rank, Race, Age, Type, Max Level, Aura, Stats.
defineType("Archangel", 4, 1, 13540, 0, 99, 3, [uint32(74), 75, 57, 99, 95], [uint32(8), 6, 8, 5, 5], [uint32(8), 10, 10, 6, 6]);
defineType("Shadowalker", 3, 4, 134, 1, 75, 4, [uint32(45), 35, 60, 80, 40], [uint32(3), 2, 10, 4, 5], [uint32(5), 5, 10, 7, 5]);
defineType("Pyromancer", 2, 0, 14, 2, 50, 1, [uint32(50), 28, 17, 40, 35], [uint32(5), 3, 2, 3, 3], [uint32(8), 4, 3, 4, 5]);
defineType("Magician", 1, 3, 224, 2, 30, 0, [uint32(35), 15, 25, 25, 30], [uint32(3), 1, 2, 2, 2], [uint32(5), 2, 3, 3, 3]);
defineType("Farmer", 0, 0, 59, 0, 15, 2, [uint32(10), 22, 8, 15, 25], [uint32(1), 2, 1, 1, 2], [uint32(1), 3, 1, 2, 3]);
}
|
0.4.18
|
// @dev Define a new hero type (class).
|
function defineType(string _className, uint8 _classRank, uint8 _classRace, uint32 _classAge, uint8 _classType, uint32 _maxLevel, uint8 _aura, uint32[5] _baseStats, uint32[5] _minIVForStats, uint32[5] _maxIVForStats)
onlyOwner
public
{
require(_classRank < 5);
require(_classType < 3);
require(_aura < 5);
require(_minIVForStats[0] <= _maxIVForStats[0] && _minIVForStats[1] <= _maxIVForStats[1] && _minIVForStats[2] <= _maxIVForStats[2] && _minIVForStats[3] <= _maxIVForStats[3] && _minIVForStats[4] <= _maxIVForStats[4]);
HeroClass memory _heroType = HeroClass({
className: _className,
classRank: _classRank,
classRace: _classRace,
classAge: _classAge,
classType: _classType,
maxLevel: _maxLevel,
aura: _aura,
baseStats: _baseStats,
minIVForStats: _minIVForStats,
maxIVForStats: _maxIVForStats,
currentNumberOfInstancedHeroes: 0
});
// Save the hero class.
heroClasses[numberOfHeroClasses] = _heroType;
// Fire event.
DefineType(msg.sender, numberOfHeroClasses, _heroType.className);
// Increment number of hero classes.
numberOfHeroClasses ++;
}
|
0.4.18
|
// @dev Mint a new hero, with _heroClassId.
|
function mint(address _owner, uint32 _heroClassId)
onlyAccessMint
public
returns (uint256)
{
require(_owner != address(0));
require(_heroClassId < numberOfHeroClasses);
// The information of the hero's class.
var _heroClassInfo = heroClasses[_heroClassId];
// Mint ERC721 token.
_mint(_owner, numberOfTokenIds);
// Build random IVs for this hero instance.
uint32[5] memory _ivForStats;
uint32[5] memory _initialStats;
for (uint8 i = 0; i < 5; i++) {
_ivForStats[i] = (random(_heroClassInfo.maxIVForStats[i] + 1, _heroClassInfo.minIVForStats[i]));
_initialStats[i] = _heroClassInfo.baseStats[i] + _ivForStats[i];
}
// Temporary hero instance.
HeroInstance memory _heroInstance = HeroInstance({
heroClassId: _heroClassId,
heroName: "",
currentLevel: 1,
currentExp: 0,
lastLocationId: 0,
availableAt: now,
currentStats: _initialStats,
ivForStats: _ivForStats
});
// Save the hero instance.
tokenIdToHeroInstance[numberOfTokenIds] = _heroInstance;
// Increment number of token ids.
// This will only increment when new token is minted, and will never be decemented when the token is burned.
numberOfTokenIds ++;
// Increment instanced number of heroes.
_heroClassInfo.currentNumberOfInstancedHeroes ++;
return numberOfTokenIds - 1;
}
|
0.4.18
|
// @dev Set where the heroes are deployed, and when they will return.
// This is intended to be called by Dungeon, Arena, Guild contracts.
|
function deploy(uint256 _tokenId, uint32 _locationId, uint256 _duration)
onlyAccessDeploy
public
returns (bool)
{
// The hero should be possessed by anybody.
require(ownerOf(_tokenId) != address(0));
var _heroInstance = tokenIdToHeroInstance[_tokenId];
// The character should be avaiable.
require(_heroInstance.availableAt <= now);
_heroInstance.lastLocationId = _locationId;
_heroInstance.availableAt = now + _duration;
// As the hero has been deployed to another place, fire event.
Deploy(msg.sender, _tokenId, _locationId, _duration);
}
|
0.4.18
|
// @dev Add exp.
// This is intended to be called by Dungeon, Arena, Guild contracts.
|
function addExp(uint256 _tokenId, uint32 _exp)
onlyAccessDeploy
public
returns (bool)
{
// The hero should be possessed by anybody.
require(ownerOf(_tokenId) != address(0));
var _heroInstance = tokenIdToHeroInstance[_tokenId];
var _newExp = _heroInstance.currentExp + _exp;
// Sanity check to ensure we don't overflow.
require(_newExp == uint256(uint128(_newExp)));
_heroInstance.currentExp += _newExp;
}
|
0.4.18
|
// @dev Level up the hero with _tokenId.
// This function is called by the owner of the hero.
|
function levelUp(uint256 _tokenId)
onlyOwnerOf(_tokenId) whenNotPaused
public
{
// Hero instance.
var _heroInstance = tokenIdToHeroInstance[_tokenId];
// The character should be avaiable. (Should have already returned from the dungeons, arenas, etc.)
require(_heroInstance.availableAt <= now);
// The information of the hero's class.
var _heroClassInfo = heroClasses[_heroInstance.heroClassId];
// Hero shouldn't level up exceed its max level.
require(_heroInstance.currentLevel < _heroClassInfo.maxLevel);
// Required Exp.
var requiredExp = getHeroRequiredExpForLevelUp(_tokenId);
// Need to have enough exp.
require(_heroInstance.currentExp >= requiredExp);
// Required Gold.
var requiredGold = getHeroRequiredGoldForLevelUp(_tokenId);
// Owner of token.
var _ownerOfToken = ownerOf(_tokenId);
// Need to have enough Gold balance.
require(addressToGoldDeposit[_ownerOfToken] >= requiredGold);
// Increase Level.
_heroInstance.currentLevel += 1;
// Increase Stats.
for (uint8 i = 0; i < 5; i++) {
_heroInstance.currentStats[i] = _heroClassInfo.baseStats[i] + (_heroInstance.currentLevel - 1) * _heroInstance.ivForStats[i];
}
// Deduct exp.
_heroInstance.currentExp -= requiredExp;
// Deduct gold.
addressToGoldDeposit[_ownerOfToken] -= requiredGold;
// Fire event.
LevelUp(msg.sender, _tokenId, _heroInstance.currentLevel);
}
|
0.4.18
|
// Need to check cases
// 1 already upgraded
// 2 first deposit (no R1)
// 3 R1 < 10, first R1.5 takes over 10 ether
// 4 R1 <= 10, second R1.5 takes over 10 ether
|
function upgradeOnePointZeroBalances() internal {
// 1
if (upgraded[msg.sender]) {
log0("account already upgraded");
return;
}
// 2
uint256 deposited = hgs.deposits(msg.sender);
if (deposited == 0)
return;
// 3
deposited = deposited.add(deposits[msg.sender]);
if (deposited.add(msg.value) < 10 ether)
return;
// 4
uint256 hgtBalance = hgt.balanceOf(msg.sender);
uint256 upgradedAmount = deposited.mul(rate).div(1 ether);
if (hgtBalance < upgradedAmount) {
uint256 diff = upgradedAmount.sub(hgtBalance);
hgt.transferFrom(reserves,msg.sender,diff);
hgtSold = hgtSold.add(diff);
upgradeHGT[msg.sender] = upgradeHGT[msg.sender].add(diff);
log0("upgraded R1 to 20%");
}
upgraded[msg.sender] = true;
}
|
0.4.16
|
/*
* Set the pool that will receive the reward token
* based on the address of the reward Token
*/
|
function setTokenPool(address _pool) public onlyGovernance {
// To buy back grain, our `targetToken` needs to be FARM
require(farm == IRewardPool(_pool).rewardToken(), "Rewardpool's token is not FARM");
profitSharingPool = _pool;
targetToken = farm;
emit TokenPoolSet(targetToken, _pool);
}
|
0.5.16
|
/**
* Sets the path for swapping tokens to the to address
* The to address is not validated to match the targetToken,
* so that we could first update the paths, and then,
* set the new target
*/
|
function setConversionPath(address from, address to, address[] memory _uniswapRoute)
public onlyGovernance {
require(from == _uniswapRoute[0],
"The first token of the Uniswap route must be the from token");
require(to == _uniswapRoute[_uniswapRoute.length - 1],
"The last token of the Uniswap route must be the to token");
uniswapRoutes[from][to] = _uniswapRoute;
}
|
0.5.16
|
/**
* Computes an address's balance of incomplete control pieces.
*
* Balances can not be transfered in the traditional way, but are instead
* computed by the amount of ArtBlocks tokens that an account directly
* holds.
*
* @param _account the address of the owner
*/
|
function balanceOf(address _account) public view override returns (uint256) {
uint256[] memory blocks = ArtBlocks(abAddress).tokensOfOwner(_account);
uint256 counter = 0;
for (uint256 i=0; i < blocks.length; i++) {
if (blocks[i] >= abRangeMin && blocks[i] <= abRangeMax) {
counter++;
}
}
return counter;
}
|
0.8.4
|
// minting rewards bonus for people who help.
|
function withdraw() public payable onlyOwner {
uint256 supply = totalSupply();
require(supply == maxSupply || block.timestamp >= headStart, "Can not withdraw yet.");
require(address(this).balance > 1 ether);
uint256 poolBalance = address(this).balance * 20 / 100;
uint256 bankBalance = address(this).balance * 30 / 100;
if(finalPay == false) {
finalPay = true;
(bool communitygrowth, ) = payable(0x5751E1e0EF3198f4AD2f5483a68dB699cBfECDD8).call{value: poolBalance}("");
require(communitygrowth);
}
//Metabank
(bool metaversebank, ) = payable(0x7cb0699dB6ff4BccC9BAd16D5156fB6EC52a9212).call{value: bankBalance}("");
require(metaversebank);
//founder
uint256 founderBalance = address(this).balance;
(bool founder1, ) = payable(0x6e49117CceF4B1bDBd3cE5118910f3D17D953843).call{value: founderBalance * 45 / 100}("");
require(founder1);
(bool founder2, ) = payable(0xA58ee9834F6D52cF936e538908449E60D9e4A6Bf).call{value: founderBalance * 225 / 1000}("");
require(founder2);
(bool founder3, ) = payable(0xfC39E340Af7600D74157E89B18D553B4590E9797).call{value: founderBalance * 20 / 100}("");
require(founder3);
(bool founder4, ) = payable(0x8B7732BCcb98a943bD275F71875fBCA63B54220a).call{value: founderBalance * 125 / 1000}("");
require(founder4);
}
|
0.8.7
|
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*/
|
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ECLR: 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);
}
|
0.7.0
|
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*/
|
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ECLR: Approver cannot be zero address");
require(spender != address(0), "ECLR: Spender cannot approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
|
0.7.0
|
/**
* Hard cap - 30000 ETH
* for token sale
*/
|
function validPurchaseTokens(uint256 _weiAmount) public inState(State.Active) returns (uint256) {
uint256 addTokens = getTotalAmountOfTokens(_weiAmount);
if (tokenAllocated.add(addTokens) > fundForSale) {
TokenLimitReached(tokenAllocated, addTokens);
return 0;
}
if (weiRaised.add(_weiAmount) > hardWeiCap) {
HardCapReached();
return 0;
}
if (_weiAmount < weiMinSale) {
return 0;
}
return addTokens;
}
|
0.4.19
|
/**
* Override for IERC2981 for optional royalty payment
* @notice Called with the sale price to determine how much royalty
* is owed and to whom.
* @param _tokenId - the NFT asset queried for royalty information
* @param _salePrice - the sale price of the NFT asset specified by _tokenId
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for _salePrice
*/
|
function royaltyInfo (
uint256 _tokenId,
uint256 _salePrice
) external view override(IERC2981) returns (
address receiver,
uint256 royaltyAmount
) {
// Royalty payment is 5% of the sale price
uint256 royaltyPmt = _salePrice*royalty/10000;
require(royaltyPmt > 0, "Royalty must be greater than 0");
return (address(this), royaltyPmt);
}
|
0.8.3
|
/**
* Override for ERC721 and ERC721URIStorage
*/
|
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
string memory _uri = super.tokenURI(tokenId);
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_uri).length > 0) {
return string(abi.encodePacked(_uri, ".json"));
}
return _uri;
}
|
0.8.3
|
/**
* Read-only function to retrieve the current NFT price in eth (flat 0.07 ETH per NFT after the free one).
* Price does not increase as quantity becomes scarce.
*/
|
function getCurrentPriceForQuantity(uint64 _quantityToMint) public view returns (uint64) {
// The first NFT is free!
if (balanceOf(msg.sender) > 0) {
return getCurrentPrice() * _quantityToMint;
} else {
return getCurrentPrice() * (_quantityToMint - freeQuantity);
}
}
|
0.8.3
|
/**
* Mint quantity of NFTs for address initiating minting
* The first mint per transaction is free to mint, however, others are 0.07 ETH per
*/
|
function mintQuantity(uint64 _quantityToMint) public payable {
require(_quantityToMint >= 1, "Minimum number to mint is 1");
require(
_quantityToMint <= getCurrentMintLimit(),
"Exceeded the max number to mint of 12."
);
require(
(_quantityToMint + totalSupply()) <= maxSupply,
"Exceeds maximum supply"
);
require((_quantityToMint + balanceOf(msg.sender)) <= maxPerWallet, "One wallet can only mint 12 NFTs");
require(
(_quantityToMint + totalSupply()) <= maxSupply,
"We've exceeded the total supply of NFTs"
);
require(
msg.value == getCurrentPriceForQuantity(_quantityToMint),
"Ether submitted does not match current price"
);
// Iterate through quantity to mint and mint each NFT
for (uint64 i = 0; i < _quantityToMint; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
}
}
|
0.8.3
|
/**
* Only 100,000 ADR for Pre-Sale!
*/
|
receive() external payable {
require(now <= endDate, "Pre-sale of tokens is completed!");
require(_totalSupply <= hardcap, "Maximum presale tokens - 100,000 ADR!");
uint tokens;
if (now <= bonusEnds) {tokens = msg.value * 250;}
else if (now > bonusEnds && now < bonusEnds1) {tokens = msg.value * 222;}
else if (now > bonusEnds1 && now < bonusEnds2) {tokens = msg.value * 200;}
else if (now > bonusEnds2 && now < bonusEnds3) {tokens = msg.value * 167;}
_beforeTokenTransfer(address(0), msg.sender, tokens);
_totalSupply = _totalSupply.add(tokens);
_balances[msg.sender] = _balances[msg.sender].add(tokens);
address(uint160(_dewpresale)).transfer(msg.value);
emit Transfer(address(0), msg.sender, tokens);
}
|
0.6.12
|
/**
* Mint quantity of NFTs for address initiating minting
* These 50 promotional mints are used by the contract owner for promotions, contests, rewards, etc.
*/
|
function mintPromotionalQuantity(uint64 _quantityToMint) public onlyOwner {
require(_quantityToMint >= 1, "Minimum number to mint is 1");
require(
(_quantityToMint + totalSupply()) <= maxSupply,
"Exceeds maximum supply"
);
// Iterate through quantity to mint and mint each NFT
for (uint64 i = 0; i < _quantityToMint; i++) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_safeMint(msg.sender, newItemId);
}
}
|
0.8.3
|
/**
* @dev Allow founder to start the Crowdsale phase1.
*/
|
function activeCrowdsalePhase1(uint256 _phase1Date) onlyOwner public {
require(isPresaleActive == true);
require(_phase1Date > endPresaleDate);
require(isPhase1CrowdsaleActive == false);
startCrowdsalePhase1Date = _phase1Date;
endCrowdsalePhase1Date = _phase1Date + 1 weeks;
isPresaleActive = !isPresaleActive;
isPhase1CrowdsaleActive = !isPhase1CrowdsaleActive;
}
|
0.4.24
|
// Deposit LP tokens to MasterChef for ADR 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.accADRPerShare).div(1e12).sub(user.rewardDebt);
safeADRTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accADRPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
|
0.6.12
|
/**
* @dev Allow founder to start the Crowdsale phase3.
*/
|
function activeCrowdsalePhase3(uint256 _phase3Date) onlyOwner public {
require(isPhase3CrowdsaleActive == false);
require(_phase3Date > endCrowdsalePhase2Date);
require(isPhase2CrowdsaleActive == true);
startCrowdsalePhase3Date = _phase3Date;
endCrowdsalePhase3Date = _phase3Date + 3 weeks;
isPhase3CrowdsaleActive = !isPhase3CrowdsaleActive;
isPhase2CrowdsaleActive = !isPhase2CrowdsaleActive;
}
|
0.4.24
|
/**
* @dev Return the state based on the timestamp.
*/
|
function getState() view public returns(State) {
if(now >= startPrivatesaleDate && isPrivatesaleActive == true) {
return State.PrivateSale;
}
if (now >= startPresaleDate && now <= endPresaleDate) {
require(isPresaleActive == true);
return State.PreSale;
}
if (now >= startCrowdsalePhase1Date && now <= endCrowdsalePhase1Date) {
require(isPhase1CrowdsaleActive == true);
return State.CrowdSalePhase1;
}
if (now >= startCrowdsalePhase2Date && now <= endCrowdsalePhase2Date) {
require(isPhase2CrowdsaleActive == true);
return State.CrowdSalePhase2;
}
if (now >= startCrowdsalePhase3Date && now <= endCrowdsalePhase3Date) {
require(isPhase3CrowdsaleActive == true);
return State.CrowdSalePhase3;
}
return State.Gap;
}
|
0.4.24
|
/**
* @dev Return the rate based on the state and timestamp.
*/
|
function getRate() view public returns(uint256) {
if (getState() == State.PrivateSale) {
return 5;
}
if (getState() == State.PreSale) {
return 6;
}
if (getState() == State.CrowdSalePhase1) {
return 7;
}
if (getState() == State.CrowdSalePhase2) {
return 8;
}
if (getState() == State.CrowdSalePhase3) {
return 10;
}
}
|
0.4.24
|
/**
* @dev Transfer the tokens to the investor address.
* @param _investorAddress The address of investor.
*/
|
function buyTokens(address _investorAddress)
public
payable
returns(bool)
{
require(whitelist.checkWhitelist(_investorAddress));
if ((getState() == State.PreSale) ||
(getState() == State.CrowdSalePhase1) ||
(getState() == State.CrowdSalePhase2) ||
(getState() == State.CrowdSalePhase3) ||
(getState() == State.PrivateSale)) {
uint256 amount;
require(_investorAddress != address(0));
require(tokenAddress != address(0));
require(msg.value >= MIN_INVESTMENT);
amount = getTokenAmount(msg.value);
require(fundTransfer(msg.value));
require(token.transfer(_investorAddress, amount));
ethRaised = ethRaised.add(msg.value);
soldToken = soldToken.add(amount);
emit TokenBought(_investorAddress,amount,now);
return true;
}else {
revert();
}
}
|
0.4.24
|
/**
* @dev See {IAbyssLockup-externalTransfer}.
*/
|
function externalTransfer(address token, address sender, address recipient, uint256 amount, uint256 abyssRequired) external onlyContract(msg.sender) returns (bool) {
if (sender == address(this)) {
IERC20(address(token)).safeTransfer(recipient, amount);
} else {
if (recipient != address(this) && abyssRequired > 0 && _freeDeposits > 0) {
_freeDeposits = _freeDeposits - 1;
}
IERC20(address(token)).safeTransferFrom(sender, recipient, amount);
}
return true;
}
|
0.8.1
|
/**
* @dev Initializes configuration of a given smart contract, with a specified
* addresses for the `safeContract` smart contracts.
*
* All three of these values are immutable: they can only be set once.
*/
|
function initialize(address safe1, address safe3, address safe7, address safe14, address safe21,
address safe28, address safe90, address safe180, address safe365) external onlyOwner returns (bool) {
require(address(safeContract1) == address(0), "AbyssLockup: already initialized");
safeContract1 = safe1;
safeContract3 = safe3;
safeContract7 = safe7;
safeContract14 = safe14;
safeContract21 = safe21;
safeContract28 = safe28;
safeContract90 = safe90;
safeContract180 = safe180;
safeContract365 = safe365;
return true;
}
|
0.8.1
|
/// Delegate your vote to the voter $(to).
|
function delegate(address to) public {
Voter storage sender = voters[msg.sender]; // assigns reference
if (sender.voted) return;
while (voters[to].delegate != address(0) && voters[to].delegate != msg.sender)
to = voters[to].delegate;
if (to == msg.sender) return;
sender.voted = true;
sender.delegate = to;
Voter storage delegateTo = voters[to];
if (delegateTo.voted)
proposals[delegateTo.vote].voteCount += sender.weight;
else
delegateTo.weight += sender.weight;
}
|
0.5.11
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.