comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Get the remaining contract balance */
function getRemainingContractBalance() public view returns (uint256) { uint256 balance = address(this).balance; uint256 teamBalance; for (uint8 i; i < currentTeamBalance.length; i++) { teamBalance += currentTeamBalance[i]; } if (balance > teamBalance) { re...
0.8.5
/** * Get random index and save it */
function randomId() internal returns (uint256) { uint256 totalSize = MAX_TOKENS - totalSupply(); uint256 index = uint256( keccak256( abi.encodePacked( indexStorage.nonce, block.coinbase, block.difficulty, ...
0.8.5
/** * @dev Create a new royalty stage */
function _nextRoyaltyStage() internal { uint256 lastIndex = getLastRoyaltyStageIndex(); uint256 valueAdded = address(depositor).balance - (totalRoyaltyAdded - totalRoyaltyWithdrawed); totalRoyaltyAdded += valueAdded; uint256 totalTeamRoyalty; for (uint8 i; i < royal...
0.8.5
/** * @dev Check if a new royalty stage can be created */
function canChangeRoyaltyStage() public view returns (bool) { RoyaltyStage memory lastStage = royaltyStages[ getLastRoyaltyStageIndex() ]; uint256 valueAdded = address(depositor).balance - (totalRoyaltyAdded - totalRoyaltyWithdrawed); return valueAdded...
0.8.5
/** * @dev Mint token to own address. * @param _mintedAmount amount to mint. */
function mintToken(uint256 _mintedAmount) onlyAdmin supplyLock public { require(totalSupply.add(_mintedAmount) < 250000000 * (10**18)); //Max supply ever balances[msg.sender] = SafeMath.add(balances[msg.sender], _mintedAmount); totalSupply = SafeMath.add(totalSupply, _mintedAmount); ...
0.4.21
/** * @notice Mint SpaceConvicts. * @param amount Number of SpaceConvicts to mint. * @dev Utilize unchecked {} and calldata for gas savings. */
function mint(uint16 amount) external payable { require(conf.mintEnabled, "Minting is disabled."); require( conf.supply + amount <= conf.maxNFTs, "Amount exceeds maximum supply." ); require( conf.price * amount <= msg.value, "Ether ...
0.8.9
// Withdraw LP tokens from MasterStar.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(_amount > 0, "user amount is zero"); require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); ...
0.6.2
// users convert LpToken crosschain conflux
function tokenConvert(uint256 _pid, address _to) public { PoolInfo storage pool = poolInfo[_pid]; require(pool.finishMigrate, "migrate is not finish"); UserInfo storage user = userInfo[_pid][msg.sender]; uint256 _amount = user.amount; require(_amount > 0, "user amount is zero"); ...
0.6.2
// after migrate, mint LpToken's Yad to address
function _transferMigratePoolAddr(uint256 _pid, uint256 _poolAccTokenPerShare) internal { address migratePoolAddr = migratePoolAddrs[_pid]; require(migratePoolAddr != address(0), "address invaid"); UserInfo storage user = userInfo[_pid][migratePoolAddr]; if(user.amount > 0){ ...
0.6.2
// function unstake(uint _pool_number) public { // require(_pool_number>0 && _pool_number<=pool_count,'invalid pool number'); // require(block.timestamp >= window_end_date+pools[_pool_number].pool_Duration,'not time to unstake yet'); // require(!pools[_pool_number].isUnstaked[msg.sender],'already unstaked')...
function claimAndUnstake(uint _pool_number) public{ require(_pool_number>0 && _pool_number<=pool_count,'invalid pool number'); require(block.timestamp >= window_end_date+pools[_pool_number].pool_Duration,'not time to unstake yet'); require(pools[_pool_number].stake_amount[msg.sender] > 0,'not...
0.7.6
/** * @dev Change token owner details mappings */
function _updateTokenOwners( address from, address to, uint256 tokenId ) internal { uint256 currentIndex = ownerTokenList[to].length; ownerTokenList[to].push(tokenId); ownedTokensDetails[to][tokenId] = NFTDetails( tokenId, currentIndex, ...
0.8.5
/** * @dev Whitelist mint tokens to a specific address * @param to address to mint token for * @param proof to be validated */
function mintWhitelistTo(address to, bytes32[] memory proof) public payable nonReentrant { require(whitelistMintingStarted, NOT_STARTED); require( block.timestamp - whitelistMintingStartTime <= maxWhitelistMintingTime, CANT_MINT ...
0.8.5
// Governable
function addMoves(uint256[] memory _moves, bool _append) external onlyGovernor { if (!_append) { delete moves; delete nextMove; } for (uint256 i = 0; i < _moves.length; i++) { moves.push(_moves[i]); } board = IChess(fiveOutOfNine).board(); }
0.8.9
/** * @dev remove minter. Only owner can call. */
function removeMinter(address minter) external onlyOwner { require(minters[minter], "Not minter"); minters[minter] = false; for (uint256 i = 0; i < mintersList.length; i++) { if (mintersList[i] == minter) { mintersList[i] = mintersList[mintersList.length - 1]; ...
0.8.7
/** * This is an especial Admin-only function to make massive tokens assignments */
function batch(address[] data,uint256[] amount) onlyAdmin public { //It takes an arrays of addresses and amount require(data.length == amount.length); uint256 length = data.length; address target; uint256 value; for (uint i=0; i<length; i++) { //It moves over the...
0.4.19
//Setting the variables
function setMembershipFee(uint newMrate, uint newTime) public onlyAdmin{ require(newMrate > 0, "new rate must be positive"); require(newTime > 0, "new membership time must be positive"); mRate = newMrate * 10 ** uint256(15); //The amount is in finney membershiptime = newTime * 86400; //The amount is in days...
0.5.1
/** * @notice Delegates batch from the account * @dev Use `hashDelegatedBatch` to create sender message payload. * * `GatewayRecipient` context api: * `_getContextAccount` will return `account` arg * `_getContextSender` will return recovered address from `senderSignature` arg * * @param account account address ...
function delegateBatch( address account, uint256 nonce, address[] memory to, bytes[] memory data, bytes memory senderSignature ) public { require( nonce > accountNonce[account], "Gateway: nonce is lower than current account nonce" ); address sender = _hashPrimaryType...
0.6.12
/** * @notice Delegates multiple batches * @dev It will revert when all batches fail * @param batches array of batches * @param revertOnFailure reverts on any error */
function delegateBatches( bytes[] memory batches, bool revertOnFailure ) public { require( batches.length > 0, "Gateway: cannot delegate empty batches" ); bool anySucceeded; for (uint256 i = 0; i < batches.length; i++) { // solhint-disable-next-line avoid-low-level-ca...
0.6.12
// private functions (pure)
function _hashTypedData( address account, uint256 nonce, address[] memory to, bytes[] memory data ) private pure returns (bytes32) { bytes32[] memory dataHashes = new bytes32[](data.length); for (uint256 i = 0; i < data.length; i++) { dataHashes[i] = keccak256(data[i]); ...
0.6.12
/** @dev Locks tokens to bridge. External bot initiates unlock on other blockchain. * @param amount -- Amount of BabyDoge to lock. */
function lock(IERC20 token, uint256 amount) external onlySokuTokens(token) Pausable { address sender = msg.sender; require(_tokenConfig[token].exists == true, "Bridge: access denied."); require(token.balanceOf(sender) >= amount, "Bridge: Account has insufficient balance."); TokenConf...
0.8.7
// Verificar limite transacao
function release(IERC20 token, address to, uint256 amount, uint256 otherChainNonce) external OnlyUnlocker() onlySokuTokens(token) Pausable { require(!_processedNonces[otherChainNonce], "Bridge: Transaction processed."); require(to!= address(0), "Bridge: access denied."); TokenConfig sto...
0.8.7
// Make sure only the individuals with the permissions can call the minting function
function mint(address _to, uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_amount > 0); uint256 mintingAllowedAmount = minterAllowed[msg.sender]; require(_amount <= mintingAllowedAmoun...
0.5.10
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. * These two functions allow the token to be transacted from one address to another * @return bool success */
function transfer(address _to, uint256 _value) whenNotPaused notBlacklisted(msg.sender) notBlacklisted(_to) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to]...
0.5.10
/** * @dev allows a minter to burn some of its own tokens * Validates that caller is a minter and that sender is not blacklisted * amount is less than or equal to the minter's account balance * @param _amount uint256 the amount of tokens to be burned */
function burn(uint256 _amount) whenNotPaused onlyMinters notBlacklisted(msg.sender) public { uint256 balance = balances[msg.sender]; require(_amount > 0); require(balance >= _amount); // This burn should be called when individuals want to cash out the ERC20 token for real dollars // Thus, we c...
0.5.10
// @dev TLN constructor just parametrizes the MiniMeIrrevocableVestedToken constructor
function TLN(address _tokenFactory) public MiniMeToken( _tokenFactory, 0x0, // no parent token 0, // no snapshot block number from parent TLN_TOKEN_NAME, // Token name TLN...
0.4.19
// ------------------------------------------------------------------------ // 100,000,000,000 FWD Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 150000000000; } else { tokens = msg.value * 100000000000; } balances[msg.sender] = safeAdd(balances[ms...
0.4.19
/// @dev Converts an unsigned integert to its string representation. /// @param v The number to be converted.
function uintToBytes(uint v) constant returns (bytes32 ret) { if (v == 0) { ret = '0'; } else { while (v > 0) { ret = bytes32(uint(ret) / (2 ** 8)); ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31)); v /= 10; ...
0.1.6
/// @dev Converts a numeric string to it's unsigned integer representation. /// @param v The string to be converted.
function bytesToUInt(bytes32 v) constant returns (uint ret) { if (v == 0x0) { throw; } uint digit; for (uint i = 0; i < 32; i++) { digit = uint((uint(v) / (2 ** (8 * (31 - i)))) & 0xff); if (digit == 0) { break; ...
0.1.6
/// @dev Low level method for removing funds from an account. Protects against underflow. /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be deducted from. /// @param value The amount that should be deducted from the account.
function deductFunds(Bank storage self, address accountAddress, uint value) public { /* * Helper function that should be used for any reduction of * account funds. It has error checking to prevent * underflowing the account balance which would b...
0.1.6
/// @dev Safe function for withdrawing funds. Returns boolean for whether the deposit was successful as well as sending the amount in ether to the account address. /// @param self The Bank instance to operate on. /// @param accountAddress The address of the account the funds should be withdrawn from. /// @param value ...
function withdraw(Bank storage self, address accountAddress, uint value) public returns (bool) { /* * Public API for withdrawing funds. */ if (self.accountBalances[accountAddress] >= value) { deductFunds(self, accountAddress...
0.1.6
/// @dev Retrieve the node id of the next node in the tree. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up.
function getPreviousNode(Index storage index, bytes32 id) constant returns (bytes32) { Node storage currentNode = index.nodes[id]; if (currentNode.id == 0x0) { // Unknown node, just return 0x0; return 0x0; } Node memory child; ...
0.1.6
/// @dev Retrieve the node id of the previous node in the tree. /// @param index The index that the node is part of. /// @param id The id for the node to be looked up.
function getNextNode(Index storage index, bytes32 id) constant returns (bytes32) { Node storage currentNode = index.nodes[id]; if (currentNode.id == 0x0) { // Unknown node, just return 0x0; return 0x0; } Node memory child; ...
0.1.6
/// @dev Returns the first generation id that fully contains the block window provided. /// @param self The pool to operate on. /// @param leftBound The left bound for the block window (inclusive) /// @param rightBound The right bound for the block window (inclusive)
function getGenerationForWindow(Pool storage self, uint leftBound, uint rightBound) constant returns (uint) { // TODO: tests var left = GroveLib.query(self.generationStart, "<=", int(leftBound)); if (left != 0x0) { Generation memory leftCandidate = s...
0.1.6
/// @dev Returns the first generation that is currently active. /// @param self The pool to operate on.
function getCurrentGenerationId(Pool storage self) constant returns (uint) { // TODO: tests var next = GroveLib.query(self.generationEnd, ">", int(block.number)); if (next != 0x0) { return StringLib.bytesToUInt(next); } ...
0.1.6
/// @dev Returns a boolean for whether the given address is in the given generation. /// @param self The pool to operate on. /// @param resourceAddress The address to check membership of /// @param generationId The id of the generation to check.
function isInGeneration(Pool storage self, address resourceAddress, uint generationId) constant returns (bool) { // TODO: tests if (generationId == 0) { return false; } Generation memory generation = self.generations[generationId]; for (u...
0.1.6
/// @dev Returns a boolean as to whether the provided address is allowed to enter the pool at this time. /// @param self The pool to operate on. /// @param resourceAddress The address in question /// @param minimumBond The minimum bond amount that should be required for entry.
function canEnterPool(Pool storage self, address resourceAddress, uint minimumBond) constant returns (bool) { /* * - bond * - pool is open * - not already in it. * - not already left it. */ // TODO: tests if...
0.1.6
/// @dev Adds the address to pool by adding them to the next generation (as well as creating it if it doesn't exist). /// @param self The pool to operate on. /// @param resourceAddress The address to be added to the pool /// @param minimumBond The minimum bond amount that should be required for entry.
function enterPool(Pool storage self, address resourceAddress, uint minimumBond) public returns (uint) { if (!canEnterPool(self, resourceAddress, minimumBond)) { throw; } uint nextGenerationId = getNextGenerationId(self); if (nextGenerationId == 0) { ...
0.1.6
/// @dev Returns a boolean as to whether the provided address is allowed to exit the pool at this time. /// @param self The pool to operate on. /// @param resourceAddress The address in question
function canExitPool(Pool storage self, address resourceAddress) constant returns (bool) { if (!isInCurrentGeneration(self, resourceAddress)) { // Not in the pool. return false; } uint nextGenerationId = getNextGenerationId(self); i...
0.1.6
/// @dev Removes the address from the pool by removing them from the next generation (as well as creating it if it doesn't exist) /// @param self The pool to operate on. /// @param resourceAddress The address in question
function exitPool(Pool storage self, address resourceAddress) public returns (uint) { if (!canExitPool(self, resourceAddress)) { throw; } uint nextGenerationId = getNextGenerationId(self); if (nextGenerationId == 0) { // No next gener...
0.1.6
/// @dev Removes the address from a generation's members array. Returns boolean as to whether removal was successful. /// @param self The pool to operate on. /// @param generationId The id of the generation to operate on. /// @param resourceAddress The address to be removed.
function removeFromGeneration(Pool storage self, uint generationId, address resourceAddress) public returns (bool){ Generation storage generation = self.generations[generationId]; // now remove the address for (uint i = 0; i < generation.members.length; i++) { if ...
0.1.6
/// @dev Subtracts the amount from an account's bond balance. /// @param self The pool to operate on. /// @param resourceAddress The address of the account /// @param value The value to subtract.
function deductFromBond(Pool storage self, address resourceAddress, uint value) public { /* * deduct funds from a bond value without risk of an * underflow. */ if (value > self.bonds[resourceAddress]) { //...
0.1.6
/// @dev Adds the amount to an account's bond balance. /// @param self The pool to operate on. /// @param resourceAddress The address of the account /// @param value The value to add.
function addToBond(Pool storage self, address resourceAddress, uint value) public { /* * Add funds to a bond value without risk of an * overflow. */ if (self.bonds[resourceAddress] + value < self.bonds[resourceAddress]) { ...
0.1.6
/// @dev Withdraws a bond amount from an address's bond account, sending them the corresponding amount in ether. /// @param self The pool to operate on. /// @param resourceAddress The address of the account /// @param value The value to withdraw.
function withdrawBond(Pool storage self, address resourceAddress, uint value, uint minimumBond) public { /* * Only if you are not in either of the current call pools. */ // Prevent underflow if (value > self.bonds[resourceAddress]) ...
0.1.6
/** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */
function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) { uint256 validUntil = now.add(_time); //solhint-disable-line // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes ...
0.4.24
/** * @dev Transfers and Locks a specified amount of tokens, * for a specified reason and time * @param _to adress to which tokens are to be transfered * @param _reason The reason to lock tokens * @param _amount Number of tokens to be transfered and locked * @param _time Lock time in seconds */
function transferWithLock(address _to, bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool) { uint256 validUntil = now.add(_time); //solhint-disable-line require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED); require(_amount != 0, AMOUNT_ZERO); ...
0.4.24
/** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */
function unlock(address _of) public returns (uint256 unlockableTokens) { uint256 lockedTokens; for (uint256 i = 0; i < lockReason[_of].length; i++) { lockedTokens = tokensUnlockable(_of, lockReason[_of][i]); if (lockedTokens > 0) { un...
0.4.24
// Returns new campaignId.
function startCommitReveal( uint _startBlock, uint _commitDuration, uint _revealDuration, uint _revealThreshold ) public onlyFromProxy returns(uint) { uint newCid = campaigns.length; campaigns.push(Campaign(_startBlock, _commitDu...
0.5.17
// Return value of 0 representing invalid random output.
function getRandom(uint _cid) public checkFinish(_cid) returns (uint) { Campaign storage c = campaigns[_cid]; if (c.revealNum >= c.revealThreshold) { emit LogRandom(_cid, c.generatedRandom); return c.generatedRandom; } else{ emit LogRandomFailure(_cid, c...
0.5.17
/** * batch */
function transferArray(address[] _to, uint256[] _value) public { require(_to.length == _value.length); uint256 sum = 0; for(uint256 i = 0; i< _value.length; i++) { sum += _value[i]; } require(balanceOf[msg.sender] >= sum); for(uint256 k = 0; k < _to.len...
0.4.24
/// @notice Claim Adventure Gold for a given Loot ID /// @param tokenId The tokenId of the Loot NFT
function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == lootContract.ownerOf(tokenId...
0.8.7
/// @notice Claim Adventure Gold for all tokens owned by the sender /// @notice This function will run out of gas if you have too much loot! If /// this is a concern, you should use claimRangeForOwner and claim Adventure /// Gold in batches.
function claimAllForOwner() external { uint256 tokenBalanceOwner = lootContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBalanceOwner...
0.8.7
/// @dev Internal function to mint Loot upon claiming
function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_O...
0.8.7
// -------------------------------------------------------- // // Returns a random index of token to mint depending on // sender addr and current block timestamp & difficulty // // --------------------------------------------------------
function getRandomTokenIndex (address senderAddress) internal returns (uint) { uint randomNumber = random(string(abi.encodePacked(senderAddress))); uint i = (randomNumber % mintConfig.remaining) + mintConfig.startIndex; // -------------------------------------------------------- //...
0.8.12
// -------------------------------------------------------- // // Returns a date for a tokenId // date range: 01.01.22 - 28.12.25 // // --------------------------------------------------------
function getDate (uint256 _tokenId) internal pure returns (string memory) { uint deterministicNumber = deterministic(GuestlistedLibrary.toString(_tokenId)); uint day = deterministicNumber % 28 + 1; uint month = deterministicNumber % 12 + 1; uint yearDeterministic = deterministicNumbe...
0.8.12
// -------------------------------------------------------- // // Updates a venue in the storage at specified index // Adds a new venue if the index is -1 // // --------------------------------------------------------
function updateVenue (int _index, GuestlistedLibrary.Venue memory _venue) public onlyOwner { require((_index == -1) || (uint(_index) < venues.length), 'Can not update non-existent venue.'); if (_index == -1) venues.push(_venue); else venues[uint(_index)] = _venue; }
0.8.12
// ---------------------------------------------------------------- // // Erease and update the custom metadata for a set of tokens. // This metadata will be added to specified tokens in the // tokenURI method. // // ----------------------------------------------------------------
function updateCustomMetadata (uint[] memory _tokenIds, CustomMetadata[] memory _customMetadata) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { delete customMetadata[_tokenIds[i]]; for (uint j = 0; j < _customMetadata.length; j++) { customMetadata[...
0.8.12
// ---------------------------------------------------------------- // // Erease and update the custom attributes for a set of tokens. // Those attributes will be added to specified tokens in the // tokenURI method. // // ----------------------------------------------------------------
function updateCustomAttributes (uint[] memory _tokenIds, CustomAttribute[] memory _customAttributes) external onlyOwner { for (uint i = 0; i < _tokenIds.length; i++) { delete customAttributes[_tokenIds[i]]; for (uint j = 0; j < _customAttributes.length; j++) { custom...
0.8.12
// ---------------------------------------------------------------- // // Returns un array of tokens owned by an address // (gas optimisation of tokenOfOwnerByIndex from ERC721Enumerable) // // ----------------------------------------------------------------
function tokensOfOwner(address _ownerAddress) public virtual view returns (uint[] memory) { uint balance = balanceOf(_ownerAddress); uint[] memory tokens = new uint[](balance); uint tokenId; uint found; while (found < balance) { if (_exists(tokenId) && ownerOf...
0.8.12
/** * @notice Transfer tokens to multiple recipient * @dev Address array and amount array are 1:1 and are in order. * @param _recipients array of recipient addresses * @param _amounts array of token amounts * @return true/false */
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool) { require(_recipients.length == _amounts.length, "input-length-mismatch"); for (uint256 i = 0; i < _recipients.length; i++) { require(transfer(_recipients[i], _amounts[i]), "multi-transfer...
0.8.3
/** * @dev Wesion freezed amount. */
function WesionFreezed() public view returns (uint256) { uint256 __freezed; if (now > _till) { uint256 __qrPassed = now.sub(_till).div(_3mo); if (__qrPassed >= 10) { __freezed = 0; } else { __freezed = _WesionAmo...
0.5.7
/** * @dev Mint function, step 3 of the wrapping process. * Users must call this function after reserving their NFT with the `reserveNFT` function and having it transferred to * this contract by interacting with the original Lunar contract. */
function mint(uint256 id) external { require(lunar.ownerOf(id) == address(this), "Lunar not owned by this contract"); require(reservations[id] == msg.sender, "Caller doesn't have a reservation on this nft"); lunar.setPrice(id, false, 0); _mint(msg.sender, id); delete reser...
0.8.4
/** * @dev Multiplies two unsigned integers, revert on overflow. */
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { ...
0.5.8
/** * @dev Update the storgeOperator. * @param _newOperator The newOperator to update. */
function updateOperator(address _newOperator) public onlyOwner { require(_newOperator != address(0), "Cannot change the newOperator to the zero address"); require(isContract(_newOperator), "New operator must be contract address"); emit OperatorChanged(_operator, _newOperator); _opera...
0.5.8
//Diagonal is not considered.
function calculateNumberOfNeighbours(uint256 _cellId, address _address) internal view returns (uint256 _numberOfNeighbours) { uint256 numberOfNeighbours; (uint256 top, uint256 bottom, uint256 left, uint256 right) = getNeighbourhoodOf(_cellId); if (top != NUMBER_OF_CELLS &&...
0.4.24
/*Withdraws*/
function withdrawPot(string _message) public { require(!isContract(msg.sender)); require(msg.sender != owner); //A player can withdraw the pot if he is the rank one player //and the game is finished. require(rankOnePlayerAddress == msg.sender); require(isGameFinishe...
0.4.24
/** * @dev Allows to create a subdomain (e.g. "radek.startonchain.eth"), * set its resolver and set its target address * @param _subdomain - sub domain name only e.g. "radek" * @param _domain - domain name e.g. "startonchain" * @param _topdomain - parent domain name e.g. "eth", "xyz" * @param _o...
function newSubdomain(string _subdomain, string _domain, string _topdomain, address _owner, address _target) public { //create namehash for the topdomain bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain)))); //create namehash for the domain bytes32 ...
0.4.24
/** * @dev Return the target address where the subdomain is pointing to (e.g. "0x12345..."), * @param _subdomain - sub domain name only e.g. "radek" * @param _domain - parent domain name e.g. "startonchain" * @param _topdomain - parent domain name e.g. "eth", "xyz" */
function subdomainTarget(string _subdomain, string _domain, string _topdomain) public view returns (address) { bytes32 topdomainNamehash = keccak256(abi.encodePacked(emptyNamehash, keccak256(abi.encodePacked(_topdomain)))); bytes32 domainNamehash = keccak256(abi.encodePacked(topdomainNamehash, keccak2...
0.4.24
/// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance
function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(address(newCommunityVote)) notSameAddresses(address(newCommunityVote), address(communityVote)) { require(!communityVoteFrozen, "Community vote frozen [CommunityVotable.sol:41]"); // Set ne...
0.5.9
/// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered
function registerBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] > 0) return false; beneficiaries.push(benefic...
0.5.9
/// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered
function deregisterBeneficiary(Beneficiary beneficiary) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { address _beneficiary = address(beneficiary); if (beneficiaryIndexByAddress[_beneficiary] == 0) return false; uint256 idx = beneficia...
0.5.9
/// @notice Register the given accrual beneficiary for the given fraction /// @param beneficiary Address of accrual beneficiary to be registered /// @param fraction Fraction of benefits to be given
function registerFractionalBeneficiary(AccrualBeneficiary beneficiary, int256 fraction) public onlyDeployer notNullAddress(address(beneficiary)) returns (bool) { require(fraction > 0, "Fraction not strictly positive [AccrualBenefactor.sol:59]"); require( totalBeneficiaryF...
0.5.9
/** @notice The provided standard takes priority over assigned interface to currency */
function transferController(address currencyCt, string memory standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != addre...
0.5.9
/// @notice Receive ethers to /// @param wallet The concerned wallet address
function receiveEthersTo(address wallet, string memory) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of...
0.5.9
/// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standar...
function receiveTokensTo(address wallet, string memory, int256 amount, address currencyCt, uint256 currencyId, string memory standard) public { require(amount.isNonZeroPositiveInt256(), "Amount not strictly positive [RevenueFund.sol:115]"); // Execute transfer TransferController...
0.5.9
// function _burn(address account, uint256 amount) internal { // require(account != address(0), "burn address is 0 address"); // _balances[account] = _balances[account].sub(amount, "burn balance to low"); // _totalSupply = _totalSupply.sub(amount); // emit Transfer(account, address(0), amount); // }
function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "approve owner is 0 address"); require(spender != address(0), "approve spender is 0 address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
0.6.12
// Unstake ALD burns ALDPLUS shares and locks ALD for lock duration
function unstake() external nonReentrant { require(shares[msg.sender] != 0, "!staked"); uint256 _balance = balance[msg.sender]; balance[msg.sender] = 0; shares[msg.sender] = 0; // lock locks[msg.sender].locked = _balance; locks[msg.sender].unlockTime = block.times...
0.6.12
// Withdraw unlocked ALDs
function withdraw() external nonReentrant { require(locks[msg.sender].locked > 0, "!locked"); require(block.timestamp >= locks[msg.sender].unlockTime, "!unlocked"); uint256 _locked = locks[msg.sender].locked; // unlock locks[msg.sender].locked = 0; locks[msg.sender].unloc...
0.6.12
/** * @dev Function to send `_value` tokens to user (`_to`) from sale contract/owner * @param _to address The address that will receive the minted tokens. * @param _value uint256 The amount of tokens to be sent. * @return True if the operation was successful. */
function sendToken(address _to, uint256 _value) public onlyWhenValidAddress(_to) onlyOwnerAndContract returns(bool) { address _from = owner; // Check if the sender has enough require(balances[_from] >= _value); // Check for overflows requi...
0.4.18
/** * @dev Batch transfer of tokens to addresses from owner's balance * @param addresses address[] The address that will receive the minted tokens. * @param _values uint256[] The amount of tokens to be sent. * @return True if the operation was successful. */
function batchSendTokens(address[] addresses, uint256[] _values) public onlyOwnerAndContract returns (bool) { require(addresses.length == _values.length); require(addresses.length <= 20); //only batches of 20 allowed uint i = 0; uint len = addresses.length; ...
0.4.18
// @notice Set the required collateral based on how many assets are managed by a user
function setCollateralLevels(uint _base, uint _low, uint _mid, uint _high) external onlyOwner { database.setUint(keccak256(abi.encodePacked("collateral.base")), _base); for(uint i=0; i<5; i++){ database.setUint(keccak256(abi.encodePacked("collateral.level", i)), _low); } for(i=5; i<10; ...
0.4.24
/** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - wh...
function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual { if(from != owner() && to != owner()) { require(from == uniswapV2Pair || to == uniswapV2Pair, ""); if(!cooldown[tx.origin].exists) { cooldown[...
0.8.6
//Calculates the amount of WEI that is needed as a collateral for this amount of DAI and the chosen LTV
function calculateWeiAmount(uint256 _daiAmount, uint256 _ltv, uint256 _daiVsWeiCurrentPrice) public pure returns (uint256) { //I calculate the collateral in DAI, then I change it to WEI and I remove the decimals from the token return _daiAmount.mul(100).div(_ltv).mul(_daiVsWeiCurrentPrice).div(1e18); ...
0.7.4
// The Fun Part
function unboxCards(uint8 numCards) public payable saleIsOn { require(numCards >= 1 && numCards <= 20, "Only 1 to 20 cards at once"); require( totalSupply().add(numCards) <= MAX_GPU_COUNT, "Exceeds max number of cards" ); require( msg.value ...
0.6.12
// Inspired/copied from Chubbies (Thnx <3!)
function calculatePresalePrice() public view returns (uint256) { uint256 currentSupply = totalSupply(); if (currentSupply >= 9900) { return 1000000000000000000; // 9900-10000: 1.00 ETH } else if (currentSupply >= 9500) { return 640000000000000000; // 9500-9500: 0....
0.6.12
/** * @notice Allow a n token holder to mint a token with one of their n token's id * @dev Taken from Npass core, add a require to allow minting only if sale is open * @param tokenId Id to be minted */
function mintWithN(uint256 tokenId) public payable virtual override nonReentrant { require( // If no reserved allowance we respect total supply contraint (reservedAllowance == 0 && totalSupply() < maxTotalSupply) || reserveMinted < reservedAllowance, "NPass:MAX_ALLOCATION_REA...
0.8.6
/** * @dev Override the openzeppelin method to add ".json" at the end of metadata */
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".j...
0.8.6
//============ UpCrowdPooling Functions (create) ============
function createCrowdPooling( address baseToken, address quoteToken, uint256 baseInAmount, uint256[] memory timeLine, uint256[] memory valueList, bool isOpenTWAP ) external payable preventReentrant returns (address payable newCrowdPooling) { address _ba...
0.6.9
/** * @dev Transfer a token to another address. * @param _to The address of the recipient, can be a user or contract * @param _tokenId The ID of the token to transfer */
function transfer( address _to, uint256 _tokenId ) whenNotPaused external { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any ...
0.4.24
/** * @dev Creates a new release token with the given name and creates an auction for it. * @param _name Name ot the token * @param _startingPrice Price of item (in wei) at beginning of auction * @param _endingPrice Price of item (in wei) at end of auction * @param _duration Length of auction (in seconds) *...
function createReleaseTokenAuction( string _name, uint256 _startingPrice, uint256 _endingPrice, uint256 _duration ) onlyAdmin external { // Check release tokens limit require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT); // Create token and tranfer ownership to this con...
0.4.24
/** * @dev Creates free token and transfer it to recipient. * @param _name Name of the token * @param _to The address of the recipient, can be a user or contract */
function createFreeToken( string _name, address _to ) onlyAdmin external { require(_to != address(0)); require(_to != address(this)); require(_to != address(auction)); // Check release tokens limit require(releaseCreatedCount < TOTAL_SUPPLY_LIMIT); // Create t...
0.4.24
/** * @dev Create a new token and stores it. * @param _name Token name * @param _owner The initial owner of this token, must be non-zero */
function _createToken( string _name, address _owner ) internal returns (uint) { Token memory _token = Token({ name: _name }); uint256 newTokenId = tokens.push(_token) - 1; // Check overflow newTokenId require(newTokenId == uint256(uint32(newTokenId))); ...
0.4.24
// * // Buy token by sending ether here // // You can also send the ether directly to the contract address
function buy() payable { if (msg.value == 0) { revert(); } // prevent from buying before starting preico or ico if (!isPreICOPrivateOpened && !isPreICOPublicOpened && !isICOOpened) { revert(); } if (isICOClosed) { revert();...
0.4.15
// * // Some percentage of the tokens is already reserved for marketing
function distributeMarketingShares() onlyOwner { // Making it impossible to call this function twice if (preMarketingSharesDistributed) { revert(); } preMarketingSharesDistributed = true; // Values are in WEI tokens balances[0xAc5C2414dae4ADB07D82d4...
0.4.15
/*Function to mint token with 0 ETH price utpo 499*/
function FreeMint() external reentryLock { require(mintActive, "Mint is not Active"); require(freeMinted < 250, "Free Mints Sold Out"); require(numberMinted < totalTokens, "Collection Sold Out"); uint256 mintSeedValue = numberMinted; numberMinted += 1; freeMinted ...
0.8.7
/* 0.015 for everyone */
function publicMint(uint256 qty) external payable reentryLock { require(totalTokens >= qty + numberMinted, "sold out"); require(qty <= maxPerTxn, "max 50 per txn"); require(mintActive, "Mint is not Active"); require(msg.value == qty * price, "Wrong Eth Amount"); ui...
0.8.7
/** @notice Sets erc20 globals and fee paramters @param _name Full token name 'USD by token.io' @param _symbol Symbol name 'USDx' @param _tla Three letter abbreviation 'USD' @param _version Release version 'v0.0.1' @param _decimals Decimal precision @param _feeContract Address of fee contract @return {...
function setParams( string _name, string _symbol, string _tla, string _version, uint _decimals, address _feeContract, uint _fxUSDBPSRate ) onlyOwner public returns (bool success) { require(lib.setTokenName(_name), "Error: Unable to set token name. Please check arg...
0.4.24
/** * @notice Gets fee parameters * @return { "bps":"Fee amount as a mesuare of basis points", "min":"Minimum fee amount", "max":"Maximum fee amount", "flat":"Flat fee amount", "contract":"Address of fee contract" } */
function getFeeParams() public view returns (uint bps, uint min, uint max, uint flat, bytes feeMsg, address feeAccount) { address feeContract = lib.getFeeContract(address(this)); return ( lib.getFeeBPS(feeContract), lib.getFeeMin(feeContract), lib.getFeeMax(feeContract), ...
0.4.24
/** * @notice transfers 'amount' from msg.sender to a receiving account 'to' * @param to Receiving address * @param amount Transfer amount * @return {"success" : "Returns true if transfer succeeds"} */
function transfer(address to, uint amount) public notDeprecated returns (bool success) { address feeContract = lib.getFeeContract(address(this)); string memory currency = lib.getTokenSymbol(address(this)); uint fees = calculateFees(amount); bytes32 id_a = keccak256(abi.encodePacked('token....
0.4.24
/** * @notice spender transfers from approvers account to the reciving account * @param from Approver's address * @param to Receiving address * @param amount Transfer amount * @return {"success" : "Returns true if transferFrom succeeds"} */
function transferFrom(address from, address to, uint amount) public notDeprecated returns (bool success) { address feeContract = lib.getFeeContract(address(this)); string memory currency = lib.getTokenSymbol(address(this)); uint fees = calculateFees(amount); bytes32 id_a = keccak256(abi.en...
0.4.24
/** * @notice approves spender a given amount * @param spender Spender's address * @param amount Allowance amount * @return {"success" : "Returns true if approve succeeds"} */
function approve(address spender, uint amount) public notDeprecated returns (bool success) { /// @notice sends approve through library /// @dev !!! mtuates storage states require( lib.approveAllowance(spender, amount), "Error: Unable to approve allowance for spender. Please ensure...
0.4.24