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 = b...
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"); requi...
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...
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%"); _tim...
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] = _...
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 * @para...
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 ) extern...
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 a...
function calculateAvailableBorrowsETH( uint256 totalCollateralInETH, uint256 totalDebtInETH, uint256 ltv ) internal pure returns (uint256) { uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv); if (availableBorrowsETH < totalDebtInETH) { return 0; } availableBo...
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 rese...
function initReserve( address aTokenImpl, address stableDebtTokenImpl, address variableDebtTokenImpl, uint8 underlyingAssetDecimals, address interestRateStrategyAddress ) public onlyPoolAdmin { address asset = ITokenConfiguration(aTokenImpl).UNDERLYING_ASSET_ADDRESS(); require( addr...
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. // ...
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 = _overflowSaf...
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(majo...
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(_ty...
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/LunyrT...
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. ...
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 < totalFr...
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).leng...
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, cl...
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 ...
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) { ...
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...
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 _isV...
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 parent...
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++; _create...
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, ...
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_G...
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]; res...
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.rewar...
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 reaso...
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 * ...
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 f...
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 ...
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 (!...
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; //...
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...
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 ...
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.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 ...
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 *...
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); ...
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 tru...
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.balanc...
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(!airdr...
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 th...
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....
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); ...
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; ...
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] = ...
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 = str...
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 clai...
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....
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]....
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);...
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....
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[ms...
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 -------------------------------------------- \ ---/ ...
function do2FriSteps( uint256 friHalfInvGroupPtr, uint256 evaluationsOnCosetPtr, uint256 cosetOffset_, uint256 friEvalPoint) internal pure returns (uint256 nextLayerValue, uint256 nextXInv) { assembly { let PRIME := 0x80000000000001100000000000000000000000000000000000000000000000...
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); ...
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 ...
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; ...
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...
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 ...
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 ...
function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); ...
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 _snaps...
function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken clone...
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 /...
function createCloneToken( address _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, ...
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 uint6...
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 && _vestin...
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); ...
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 tok...
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 p...
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; // ...
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 ve...
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; ...
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) { addres...
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);...
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....
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 ...
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(...
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...
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 t...
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 b...
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; ...
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.availableA...
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 ...
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 ...
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) { ...
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 = ad...
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); ...
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...
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; } ...
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 receive...
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(royaltyPm...
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.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 + tota...
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 <...
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 ...
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; ...
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.rewardD...
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 = _phase3...
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...
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() ...
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) || ...
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 != a...
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"); ...
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; ...
0.5.11