comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Transfers contract/tokenId into contract and issues wrapping token. */
function wrap(address contract_, uint256 tokenId) external virtual override nonReentrant { require(IERC721(contract_).ownerOf(tokenId) == msg.sender, 'ERC721Wrapper: Caller must own NFT.'); require(IERC721(contract_).getApproved(tokenId) == address(this), 'ERC721Wrapper: Contract must be given approval to wrap NFT.'); require(isWrappable(contract_, tokenId), 'ERC721Wrapper: TokenId not within approved range.'); IERC721(contract_).transferFrom(msg.sender, address(this), tokenId); _wrap(msg.sender, tokenId); }
0.8.4
/** * @dev Updates approved contract/token ranges. Simple access control mechanism. */
function _updateApprovedTokenRanges(address contract_, uint256 minTokenId, uint256 maxTokenId) internal virtual { require(minTokenId <= maxTokenId, 'ERC721Wrapper: Min tokenId must be less-than/equal to max.'); if (_approvedTokenRanges[contract_].maxTokenId == 0) { _approvedTokenRanges[contract_] = TokenIdRange(minTokenId, maxTokenId); } else { _approvedTokenRanges[contract_].minTokenId = minTokenId; _approvedTokenRanges[contract_].maxTokenId = maxTokenId; } }
0.8.4
/** * @dev Transfers tokenIds to rental pool and returns an ERC721 receipt to owner * @param erc721Address Address of supported ERC721 NFT (only erc721 is supported in v1) * @param tokenIds TokenIds to be staked within the contract * @param rentalFees Fees charged per token rental (in gwei) */
function addStaked( address erc721Address, uint16[] calldata tokenIds, uint80[] calldata rentalFees ) external whenNotPaused { uint256 _nftIndex = getAirSupportIndex(erc721Address); require(tokenIds.length == rentalFees.length, 'Token and fee mismatch'); // Verify ownership and fees, Update storage; Transfer staked colors; Issue Receipt for (uint256 i = 0; i < tokenIds.length; i++) { require( msg.sender == IERC721Enumerable(erc721Address).ownerOf(tokenIds[i]), 'Token not owned by caller' ); verifyFee(erc721Address, rentalFees[i]); AirNFTStorage .flashableNFT[_nftIndex + tokenIds[i]] .rentalFee = rentalFees[i]; IERC721Enumerable(erc721Address).transferFrom( msg.sender, address(this), tokenIds[i] ); _safeMint(msg.sender, _nftIndex + tokenIds[i]); } emit stakeEvent(msg.sender, tokenIds, rentalFees); }
0.8.4
/** * @dev Removes tokenIds from rental pool and returns them to owner + burns receipt token * @param erc721Address Address of ERC721 NFT (only erc721 is supported in v1) * @param tokenIds tokens staked within the contract * @param claimRoyalties supplied boolean true will claim royalties for those tokens removed from staking */
function removeStaked( address erc721Address, uint16[] calldata tokenIds, bool claimRoyalties ) external whenNotPaused { uint256 _nftIndex = getAirSupportIndex(erc721Address); // Withdraw accruals (optional) if (claimRoyalties) { claim(erc721Address, tokenIds); } // Verify receipt holder; Transfer tokens; burn receipt for (uint256 i = 0; i < tokenIds.length; i++) { verifyReceiptOwnership(_nftIndex + tokenIds[i]); IERC721Enumerable(erc721Address).safeTransferFrom( address(this), msg.sender, tokenIds[i] ); _burn(_nftIndex + tokenIds[i]); } emit unstakeEvent(msg.sender, tokenIds); }
0.8.4
/** * @dev Updates rental fee for supplied tokenIds * @param nftAddress Address of supported NFT * @param tokenIds TokenIds staked within the contract * @param rentalFees Fees charged per token rental (in gwei) */
function updateRentalFees( address nftAddress, uint16[] calldata tokenIds, uint80[] calldata rentalFees ) public whenNotPaused { uint256 _nftIndex = getAirSupportIndex(nftAddress); require(tokenIds.length == rentalFees.length, 'Token and fee mismatch'); // Verify receipt + fees; Update storage for (uint256 i = 0; i < tokenIds.length; i++) { verifyReceiptOwnership(_nftIndex + tokenIds[i]); verifyFee(nftAddress, rentalFees[i]); AirNFTStorage .flashableNFT[_nftIndex + tokenIds[i]] .rentalFee = rentalFees[i]; } }
0.8.4
/** * @dev Mints Sync x Colors NFT with staked COLORS NFT tokens. * @param mintAmount Amount to mint * @param tokenIds tokenIds of COLORS NFT to apply to mint */
function mintSyncsWithRentedTokens( uint16 mintAmount, uint16[] calldata tokenIds ) external payable whenNotPaused { require(tokenIds.length <= 3, 'Num COLORS must be <=3'); uint256 mintPrice = 0.05 ether; uint256 _nftIndex = 10**16; // Avoid an MLoad here since the Colors contract is predetermined to be within slot 1 // Calculte fees; Update accrued royalties uint256 totalRentalFee = updateRoyalties( _nftIndex, tokenIds, uint80(mintAmount) ); require( msg.value == mintAmount * mintPrice + totalRentalFee, 'Insufficient funds.' ); // Mint to contract address ISYNC(SYNCXCOLORS).mint{value: mintAmount * mintPrice}( mintAmount, tokenIds ); // Transfer NFTs to the sender uint256 new_supply = IERC721Enumerable(SYNCXCOLORS).totalSupply(); for (uint256 i = new_supply - mintAmount; i < new_supply; i++) { IERC721Enumerable(SYNCXCOLORS).safeTransferFrom( address(this), msg.sender, i ); } emit mintEvent(msg.sender, tokenIds, mintAmount, totalRentalFee); }
0.8.4
/** * @dev Updates colors of Sync x Colors NFT with staked COLORS NFT tokens * @param tokenIds Sync x Colors tokens to recolor * @param colorsTokenIds COLORS NFT tokenIds to apply to recolor */
function updateSyncColors( uint16[] calldata tokenIds, uint16[] calldata colorsTokenIds ) external payable whenNotPaused { require(colorsTokenIds.length <= 3, 'Num COLORS must be <=3'); uint256 resyncPrice = 0.005 ether; uint256 _nftIndex = 10**16; // Avoid an MLoad here since the Colors contract is predetermined to be at first airSupportIndex // Verify ownership, for (uint256 i = 0; i < tokenIds.length; i++) { require( msg.sender == IERC721Enumerable(SYNCXCOLORS).ownerOf(tokenIds[i]), 'SYNC not owned by sender' ); } // Verify staked colors; update storage; calculate fees uint96 totalRentalFee = updateRoyalties( _nftIndex, colorsTokenIds, uint80(tokenIds.length) ); require( msg.value == tokenIds.length * resyncPrice + totalRentalFee, 'Insufficient funds' ); // Transfer sync, updateColors, transfer sync back to sender for (uint256 i = 0; i < tokenIds.length; i++) { IERC721Enumerable(SYNCXCOLORS).transferFrom( msg.sender, address(this), tokenIds[i] ); ISYNC(SYNCXCOLORS).updateColors{value: 0.005 ether}( tokenIds[i], colorsTokenIds ); IERC721Enumerable(SYNCXCOLORS).transferFrom( address(this), msg.sender, tokenIds[i] ); } emit recolorEvent(msg.sender, tokenIds, colorsTokenIds, totalRentalFee); }
0.8.4
/** * @dev Update royalty balances and calculate total fees for the loan * @param _nftIndex NFT index * @param tokenIds Tokens to be loaned * @param size Number of uses to be applied to each loaned token # @return airSupportIndex of NFT represented by receipt token ID */
function updateRoyalties( uint256 _nftIndex, uint16[] memory tokenIds, uint80 size ) internal returns (uint96) { uint96 royaltyFee; flashableNFTStruct memory rentalNFT; for (uint256 i = 0; i < tokenIds.length; i++) { require(_exists(_nftIndex + tokenIds[i]), 'COLORS tokenId unavailable'); rentalNFT = AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]]; AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].allTimeAccruals = rentalNFT.allTimeAccruals + rentalNFT.rentalFee * size; AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals = rentalNFT.accruals + rentalNFT.rentalFee * size; AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].allTimeLends = rentalNFT.allTimeLends + uint16(size); royaltyFee += rentalNFT.rentalFee; } uint96 totalRentalFee = (royaltyFee * uint96(size) * platformFeeRate) / 1000; AirNFTStorage.platformAccruals += totalRentalFee - royaltyFee * uint96(size); return totalRentalFee; }
0.8.4
/** * @dev tokenURI function * @param tokenId tokenId of receipt * @return returns URI of receipt token */
function tokenURI(uint256 tokenId) public view override returns (string memory) { require( _exists(tokenId), 'ERC721Metadata: URI query for nonexistent token..' ); uint256 nftIndex = receiptIndex(tokenId); uint256 nftTokenId = tokenId - nftIndex; address nftAddress = AirNFTStorage.airSupportNFTAddress[nftIndex]; string memory nftName = IERC721MetaData(nftAddress).name(); bytes memory nftColor = getReceiptColor(nftAddress, nftTokenId); string memory receiptImage = Base64.encode( printReceipt(nftName, nftTokenId, nftColor) ); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{', '"image":"', 'data:image/svg+xml;base64,', receiptImage, '",', '"description":"AIR NFT Lender Staking Receipt"', ',', '"attributes":[', '{"trait_type":"Collection","value":"', nftName, '"},', '{"trait_type":"tokenID","value":"', tokenId.toString(), '"}]}' ) ) ) ) ); }
0.8.4
/** * @dev Produces the receipt token image for tokenURI * @param nftName Name of NFT to be printed on the receipt * @param tokenId tokenId to be printed on the receipt * @return returns SVG as bytes */
function printReceipt( string memory nftName, uint256 tokenId, bytes memory color ) internal pure returns (bytes memory) { return abi.encodePacked( '<svg xmlns="http://www.w3.org/2000/svg" width="320" height="450" viewbox="0 0 320 450" style="background-color:#FFFFFF">', '<g id= "2"> <path d = "M20 400L20 30L40 30L60 60L100 30L120 30L140 60L180 30L200 30L220 60L260 30L280 30L300 60L300 220" ', 'stroke="black" fill="', color, '" stroke-width="15"/><path d = "M300 60L300 400" stroke="black" stroke-width="30"/>', '</g><use href="#2" x="0" y="0" transform="scale(1,-1) translate(0,-450)"/>', '<path d = "M60 310L260 310" stroke="black" stroke-width="15"/><path d = "M60 260L260 260" stroke="black" stroke-width="15"/>', '<text x="50" y="180" font-size="8em">AIR</text><text x="60" y="245" font-size="1em">', nftName, '</text><text x="60" y="295" font-size="1em">TokenID #', tokenId.toString(), '</text><text x="60" y="355" font-size="1em">Redeemable at SyncxColors.xyz</text>', '<text x="60" y="375" font-size="1em">Powered by AirNFT</text></svg>' ); }
0.8.4
/** * @dev Get color for receipt * @param nftAddress Address of NFT for receipt * @param tokenId tokenId of NFT for receipt * @return returns hex color string as bytes */
function getReceiptColor(address nftAddress, uint256 tokenId) internal view returns (bytes memory) { if (nftAddress == THE_COLORS) { return bytes(ITheColors(THE_COLORS).getHexColor(tokenId)); } else { return '#DDDDDD'; // Future: For other collections, generate colors by hash of uri. } }
0.8.4
/** * @dev Withdraws all royalties accrued by the calling address (based on receipts held) * @param nftAddress Nft address */
function claimAllContract(address nftAddress) public whenNotPaused { uint256 _nftIndex = getAirSupportIndex(nftAddress); uint256 royalties; uint256 bal = balanceOf(msg.sender); uint256 receiptTokenId; for (uint256 i = 0; i < bal; i++) { receiptTokenId = tokenOfOwnerByIndex(msg.sender, i); if (receiptIndex(receiptTokenId) == _nftIndex) { royalties += AirNFTStorage.flashableNFT[receiptTokenId].accruals; AirNFTStorage.flashableNFT[receiptTokenId].accruals = 0; } } _claim(royalties); }
0.8.4
/** * @dev External Facing: Withdraws royalties accrued for the supplied tokenIds (based on receipts held) * @param nftAddress Address of NFT * @param tokenIds tokenIds staked within the contract */
function claim(address nftAddress, uint16[] calldata tokenIds) public whenNotPaused { uint256 _nftIndex = getAirSupportIndex(nftAddress); uint256 royalties; for (uint256 i = 0; i < tokenIds.length; i++) { verifyReceiptOwnership(_nftIndex + tokenIds[i]); royalties += AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals; AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]].accruals = 0; } _claim(royalties); }
0.8.4
/** * @dev Returns total rental cost for supplied tokenIds * @param nftAddress Address of NFT * @param tokenIds tokens staked within the contract * @return Total rental cost (in gwei) */
function getRentalCost(address nftAddress, uint16[] calldata tokenIds) public view returns (uint256) { uint256 _nftIndex = getAirSupportIndex(nftAddress); uint256 rentalFee = 0; for (uint256 i = 0; i < tokenIds.length; i++) { rentalFee += AirNFTStorage .flashableNFT[_nftIndex + tokenIds[i]] .rentalFee; } return (rentalFee * platformFeeRate) / 1000; }
0.8.4
/** * @dev Convenience function which returns supported ERC721 tokenIds owned by calling address * @param erc721Address Address of ERC721 NFT * @param request Address of owner queried * @return Array of tokenIds */
function getOwnedERC721ByAddress(address erc721Address, address request) public view returns (uint256[] memory) { require( AirNFTStorage.airSupportIndex[erc721Address] != 0, 'NFT unsupported' ); uint256 bal = IERC721Enumerable(erc721Address).balanceOf(request); uint256[] memory tokenIds = new uint256[](bal); for (uint256 i = 0; i < bal; i++) { tokenIds[i] = IERC721Enumerable(erc721Address).tokenOfOwnerByIndex( request, i ); } return tokenIds; }
0.8.4
/** * @dev Returns NFT tokenIds staked by calling address (based on receipts held) * @param nftAddress Address of ERC721 NFT * @param stakerAddress Address of staker * @return Array of tokenIds */
function getStakedByAddress(address nftAddress, address stakerAddress) public view returns (uint256[] memory) { uint256 _nftIndex = getAirSupportIndex(nftAddress); uint256 bal = balanceOf(stakerAddress); uint256[] memory staked = new uint256[](bal); uint256 receiptTokenId; uint256 index; for (uint256 i = 0; i < bal; i++) { receiptTokenId = tokenOfOwnerByIndex(stakerAddress, i); if (receiptIndex(receiptTokenId) == _nftIndex) { staked[index] = receiptTokenId - _nftIndex; index++; } } // Trim the array before returning it return trimmedArray(staked, index); }
0.8.4
/** * @dev Returns all ERC721 tokenIds currently staked * @param nftAddress Address of ERC721 NFT * @return Array of tokenIds */
function getStaked(address nftAddress) public view returns (uint256[] memory) { uint256 _nftIndex = getAirSupportIndex(nftAddress); uint256 supply = totalSupply(); uint256[] memory staked = new uint256[](supply); uint256 receiptTokenId; uint256 index; for (uint256 i = 0; i < supply; i++) { receiptTokenId = tokenByIndex(i); if (receiptIndex(receiptTokenId) == _nftIndex) { staked[index] = receiptTokenId - _nftIndex; index++; } } // Trim the array before returning it return trimmedArray(staked, index); }
0.8.4
/** * @dev Returns royalty accruals by address of Staker (based on receipts held) * @param stakerAddress Address of token staker * @return Total royalties accrued (in gwei) */
function getAccruals(address stakerAddress) public view returns (uint256) { uint256 royalties; uint256 bal = balanceOf(stakerAddress); for (uint256 i = 0; i < bal; i++) { royalties += AirNFTStorage .flashableNFT[tokenOfOwnerByIndex(stakerAddress, i)] .accruals; } return royalties; }
0.8.4
/** * @dev Returns statistics for the staked ERC721 tokenId * @param nftAddress Address of ERC721 NFT * @param tokenIds tokenIds * @return Array of flashableNFTStruct structs */
function stakedNFTData(address nftAddress, uint256[] calldata tokenIds) public view returns (flashableNFTStruct[] memory) { uint256 _nftIndex = getAirSupportIndex(nftAddress); flashableNFTStruct[] memory stakedStructs = new flashableNFTStruct[]( tokenIds.length ); for (uint256 i = 0; i < tokenIds.length; i++) { stakedStructs[i] = AirNFTStorage.flashableNFT[_nftIndex + tokenIds[i]]; } return stakedStructs; }
0.8.4
/** * @dev Adds NFT contract address to supported staking NFTs * @param nftAddress Address of NFT */
function addSupportedNFT(address nftAddress, uint96 _minimumFlashFee) public onlyOwner { require( AirNFTStorage.airSupportIndex[nftAddress] == 0, 'NFT already supported' ); // Each additional NFT index is incremented by 10**16 uint64 index = AirNFTStorage.currentIndex + 10**16; AirNFTStorage.currentIndex = index; AirNFTStorage.airSupportIndex[nftAddress] = index; AirNFTStorage.airSupportNFTAddress[index] = nftAddress; minimumFlashFee[nftAddress] = _minimumFlashFee; }
0.8.4
/** * @dev Trims inputArray to size length */
function trimmedArray(uint256[] memory inputArray, uint256 length) internal pure returns (uint256[] memory) { uint256[] memory outputArray = new uint256[](length); for (uint256 i = 0; i < length; i++) { outputArray[i] = inputArray[i]; } return outputArray; }
0.8.4
/* Burn Jane by User */
function burn(uint256 _value) returns (bool success) { if (balanceOf[msg.sender] < _value) revert(); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; }
0.4.16
/* Burn Janes from Users */
function burnFrom(address _from, uint256 _value) returns (bool success) { if (balanceOf[_from] < _value) revert(); // Check if the sender has enough if (_value > allowance[_from][msg.sender]) revert(); // Check allowance balanceOf[_from] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(_from, _value); return true; }
0.4.16
/** * @dev Performs all the functionalities that are enabled. */
function _afterTokenTransfer(ValuesFromAmount memory values, bool selling, bool buying) internal virtual { if (buying || selling) { if (_autoBurnEnabled) { _tokenBalances[address(this)] += values.tBurnFee; _reflectionBalances[address(this)] += values.rBurnFee; _approve(address(this), _msgSender(), values.tBurnFee); burnFrom(address(this), values.tBurnFee); } if (_marketingRewardEnabled) { _tokenBalances[address(this)] += values.tMarketingFee; _reflectionBalances[address(this)] += values.rMarketingFee; _marketingTokensToSwap += values.tMarketingFee; } if (_rewardEnabled) { _distributeFee(values.rRewardFee, values.tRewardFee); } } if (!buying && selling && values.amount >= getReservePercent(maxSellAmountNormalTax) && values.amount < getReservePercent(maxSellAmountPercent)) { if (_autoSwapAndLiquifyEnabled) { // add liquidity fee to this contract. _tokenBalances[address(this)] += values.tLiquifyFee; _reflectionBalances[address(this)] += values.rLiquifyFee; } } }
0.8.3
/** * @dev Performs transfer between two accounts that are both excluded in receiving reward. */
function _transferBothExcluded(address sender, address recipient, ValuesFromAmount memory values) private { _tokenBalances[sender] = _tokenBalances[sender] - values.amount; _reflectionBalances[sender] = _reflectionBalances[sender] - values.rAmount; _tokenBalances[recipient] = _tokenBalances[recipient] + values.tTransferAmount; _reflectionBalances[recipient] = _reflectionBalances[recipient] + values.rTransferAmount; }
0.8.3
/** * @dev Includes an account from receiving reward. * * Emits a {IncludeAccountInReward} event. * * Requirements: * * - `account` is excluded in receiving reward. */
function includeAccountInReward(address account) public onlyOwner { require(_isExcludedFromReward[account], "Account is already included."); for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_excludedFromReward[i] == account) { _excludedFromReward[i] = _excludedFromReward[_excludedFromReward.length - 1]; _tokenBalances[account] = 0; _isExcludedFromReward[account] = false; _excludedFromReward.pop(); break; } } emit IncludeAccountInReward(account); }
0.8.3
/** * @dev Airdrop tokens to all holders that are included from reward. * Requirements: * - the caller must have a balance of at least `amount`. */
function airdrop(uint256 amount) public whenNotPaused { address sender = _msgSender(); //require(!_isExcludedFromReward[sender], "Excluded addresses cannot call this function"); require(!isBlacklisted[_msgSender()], "Blacklisted address"); require(balanceOf(sender) >= amount, "The caller must have balance >= amount."); ValuesFromAmount memory values = _getValues(amount, false, false, false); if (_isExcludedFromReward[sender]) { _tokenBalances[sender] -= values.amount; } _reflectionBalances[sender] -= values.rAmount; _reflectionTotal = _reflectionTotal - values.rAmount; _totalRewarded += amount; emit Airdrop(amount); }
0.8.3
/** * @dev Returns the reflected amount of a token. * Requirements: * - `amount` must be less than total supply. */
function reflectionFromToken(uint256 amount, bool deductTransferFee, bool selling, bool buying) internal view returns(uint256) { require(amount <= _totalSupply, "Amount must be less than supply"); ValuesFromAmount memory values = _getValues(amount, deductTransferFee, selling, buying); return values.rTransferAmount; }
0.8.3
/** * @dev Swap half of contract's token balance for ETH, * and pair it up with the other half to add to the * liquidity pool. * * Emits {SwapAndLiquify} event indicating the amount of tokens swapped to eth, * the amount of ETH added to the LP, and the amount of tokens added to the LP. */
function swapAndLiquify(uint256 contractBalance) private lockTheSwap { // Split the contract balance into two halves. uint256 tokensToSwap = contractBalance / 2; uint256 tokensAddToLiquidity = contractBalance - tokensToSwap; // Contract's current ETH balance. uint256 initialBalance = address(this).balance; // Swap half of the tokens to ETH. swapTokensForEth(tokensToSwap, address(this)); // Figure out the exact amount of tokens received from swapping. uint256 ethAddToLiquify = address(this).balance - initialBalance; // Add to the LP of this token and WETH pair (half ETH and half this token). addLiquidity(ethAddToLiquify, tokensAddToLiquidity); _totalETHLockedInLiquidity += address(this).balance - initialBalance; _totalTokensLockedInLiquidity += contractBalance - balanceOf(address(this)); emit SwapAndLiquify(tokensToSwap, ethAddToLiquify, tokensAddToLiquidity); }
0.8.3
/** * @dev Swap `amount` tokens for ETH and send to `to` * * Emits {Transfer} event. From this contract to the token and WETH Pair. */
function swapTokensForEth(uint256 amount, address to) private { // Generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = _uniswapV2Router.WETH(); _approve(address(this), address(_uniswapV2Router), amount); // Swap tokens to ETH _uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, to, block.timestamp + 60 * 1000 ); }
0.8.3
/** * @dev Add `ethAmount` of ETH and `tokenAmount` of tokens to the LP. * Depends on the current rate for the pair between this token and WETH, * `ethAmount` and `tokenAmount` might not match perfectly. * Dust(leftover) ETH or token will be refunded to this contract * (usually very small quantity). * * Emits {Transfer} event. From this contract to the token and WETH Pai. */
function addLiquidity(uint256 ethAmount, uint256 tokenAmount) private { _approve(address(this), address(_uniswapV2Router), tokenAmount); // Add the ETH and token to LP. // The LP tokens will be sent to burnAccount. // No one will have access to them, so the liquidity will be locked forever. _uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable burnAccount, // the LP is sent to burnAccount. block.timestamp + 60 * 1000 ); }
0.8.3
/** * @dev Returns fees and transfer amount in both tokens and reflections. * tXXXX stands for tokenXXXX * rXXXX stands for reflectionXXXX * More details can be found at comments for ValuesForAmount Struct. */
function _getValues(uint256 amount, bool deductTransferFee, bool selling, bool buying) private view returns (ValuesFromAmount memory) { ValuesFromAmount memory values; values.amount = amount; _getTValues(values, deductTransferFee, selling, buying); _getRValues(values, deductTransferFee, selling, buying); return values; }
0.8.3
/** * @dev Adds fees and transfer amount in tokens to `values`. * tXXXX stands for tokenXXXX * More details can be found at comments for ValuesForAmount Struct. */
function _getTValues(ValuesFromAmount memory values, bool deductTransferFee, bool selling, bool buying) view private { if (deductTransferFee) { values.tTransferAmount = values.amount; } else { // calculate fee if (buying || selling) { values.tBurnFee = _calculateTax(values.amount, _taxBurn, _taxBurnDecimals); values.tMarketingFee = _calculateTax(values.amount, _taxMarketing, _taxMarketingDecimals); values.tRewardFee = _calculateTax(values.amount, _taxReward, _taxRewardDecimals); } if (!buying && selling && values.amount >= getReservePercent(maxSellAmountNormalTax) && values.amount < getReservePercent(maxSellAmountPercent)) { values.tLiquifyFee = _calculateTax(values.amount, _taxLiquify, _taxLiquifyDecimals); } // amount after fee values.tTransferAmount = values.amount - values.tBurnFee - values.tRewardFee - values.tLiquifyFee - values.tMarketingFee; } }
0.8.3
/** * @dev Returns the current reflection supply and token supply. */
function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _reflectionTotal; uint256 tSupply = _totalSupply; for (uint256 i = 0; i < _excludedFromReward.length; i++) { if (_reflectionBalances[_excludedFromReward[i]] > rSupply || _tokenBalances[_excludedFromReward[i]] > tSupply) return (_reflectionTotal, _totalSupply); rSupply = rSupply - _reflectionBalances[_excludedFromReward[i]]; tSupply = tSupply - _tokenBalances[_excludedFromReward[i]]; } if (rSupply < _reflectionTotal / _totalSupply) return (_reflectionTotal, _totalSupply); return (rSupply, tSupply); }
0.8.3
/** * @dev Enables the auto burn feature. * Burn transaction amount * `taxBurn_` amount of tokens each transaction when enabled. * * Emits a {EnabledAutoBurn} event. * * Requirements: * * - auto burn feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */
function enableAutoBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(!_autoBurnEnabled, "Auto burn feature is already enabled."); require(taxBurn_ > 0, "Tax must be greater than 0."); require(taxBurnDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _autoBurnEnabled = true; setTaxBurn(taxBurn_, taxBurnDecimals_); emit EnabledAutoBurn(); }
0.8.3
/** * @dev Enables the reward feature. * Distribute transaction amount * `taxReward_` amount of tokens each transaction when enabled. * * Emits a {EnabledReward} event. * * Requirements: * * - reward feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */
function enableReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(!_rewardEnabled, "Reward feature is already enabled."); require(taxReward_ > 0, "Tax must be greater than 0."); require(taxRewardDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _rewardEnabled = true; setTaxReward(taxReward_, taxRewardDecimals_); emit EnabledReward(); }
0.8.3
/** * @dev Enables the auto swap and liquify feature. * Swaps half of transaction amount * `taxLiquify_` amount of tokens * to ETH and pair with the other half of tokens to the LP each transaction when enabled. * * Emits a {EnabledAutoSwapAndLiquify} event. * * Requirements: * * - auto swap and liquify feature mush be disabled. * - tax must be greater than 0. * - tax decimals + 2 must be less than token decimals. * (because tax rate is in percentage) */
function enableAutoSwapAndLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_, address routerAddress, uint256 minTokensBeforeSwap_) public onlyOwner { require(!_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature is already enabled."); require(taxLiquify_ > 0, "Tax must be greater than 0."); require(taxLiquifyDecimals_ + 2 <= decimals(), "Tax decimals must be less than token decimals - 2"); _minTokensBeforeSwap = minTokensBeforeSwap_; initSwap(routerAddress); // enable _autoSwapAndLiquifyEnabled = true; setTaxLiquify(taxLiquify_, taxLiquifyDecimals_); emit EnabledAutoSwapAndLiquify(); }
0.8.3
/** * @dev Updates taxBurn * * Emits a {TaxBurnUpdate} event. * * Requirements: * * - auto burn feature must be enabled. * - total tax rate must be less than 100%. */
function setTaxBurn(uint8 taxBurn_, uint8 taxBurnDecimals_) public onlyOwner { require(_autoBurnEnabled, "Auto burn feature must be enabled. Try the EnableAutoBurn function."); uint8 previousTax = _taxBurn; uint8 previousDecimals = _taxBurnDecimals; _taxBurn = taxBurn_; _taxBurnDecimals = taxBurnDecimals_; emit TaxBurnUpdate(previousTax, previousDecimals, taxBurn_, taxBurnDecimals_); }
0.8.3
/** * @dev Updates taxReward * * Emits a {TaxRewardUpdate} event. * * Requirements: * * - reward feature must be enabled. * - total tax rate must be less than 100%. */
function setTaxReward(uint8 taxReward_, uint8 taxRewardDecimals_) public onlyOwner { require(_rewardEnabled, "Reward feature must be enabled. Try the EnableReward function."); uint8 previousTax = _taxReward; uint8 previousDecimals = _taxRewardDecimals; _taxReward = taxReward_; _taxRewardDecimals = taxRewardDecimals_; emit TaxRewardUpdate(previousTax, previousDecimals, taxReward_, taxRewardDecimals_); }
0.8.3
/** * @dev Updates taxLiquify * * Emits a {TaxLiquifyUpdate} event. * * Requirements: * * - auto swap and liquify feature must be enabled. * - total tax rate must be less than 100%. */
function setTaxLiquify(uint8 taxLiquify_, uint8 taxLiquifyDecimals_) public onlyOwner { require(_autoSwapAndLiquifyEnabled, "Auto swap and liquify feature must be enabled. Try the EnableAutoSwapAndLiquify function."); uint8 previousTax = _taxLiquify; uint8 previousDecimals = _taxLiquifyDecimals; _taxLiquify = taxLiquify_; _taxLiquifyDecimals = taxLiquifyDecimals_; emit TaxLiquifyUpdate(previousTax, previousDecimals, taxLiquify_, taxLiquifyDecimals_); }
0.8.3
// Possible ways this could break addressed // 1) No agreement to terms - added require // 2) Adding liquidity after LGE is over - added require // 3) Overflow from uint - impossible there is not enough ETH available // 4) Depositing 0 - not an issue it will just add 0 totally
function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable { require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here totalETHContributed = totalETHContributed.add(msg.value); // For front end display during LGE. This resets with definitive correct balance while calling pair. emit LiquidityAddition(msg.sender, msg.value); }
0.6.12
/** *@dev list allows a party to place an order on the orderbook *@param _tokenadd address of the drct tokens *@param _amount number of DRCT tokens *@param _price uint256 price of all tokens in wei */
function list(address _tokenadd, uint256 _amount, uint256 _price) external { require(blacklist[msg.sender] == false); require(_price > 0); ERC20_Interface token = ERC20_Interface(_tokenadd); require(totalListed[msg.sender][_tokenadd] + _amount <= token.allowance(msg.sender,address(this))); if(forSale[_tokenadd].length == 0){ forSale[_tokenadd].push(0); } forSaleIndex[order_nonce] = forSale[_tokenadd].length; forSale[_tokenadd].push(order_nonce); orders[order_nonce] = Order({ maker: msg.sender, asset: _tokenadd, price: _price, amount:_amount }); emit OrderPlaced(order_nonce,msg.sender,_tokenadd,_amount,_price); if(openBookIndex[_tokenadd] == 0 ){ openBookIndex[_tokenadd] = openBooks.length; openBooks.push(_tokenadd); } userOrderIndex[order_nonce] = userOrders[msg.sender].length; userOrders[msg.sender].push(order_nonce); totalListed[msg.sender][_tokenadd] += _amount; order_nonce += 1; }
0.4.24
//Then you would have a mapping from an asset to its price/ quantity when you list it.
function listDda(address _asset, uint256 _amount, uint256 _price, bool _isLong) public onlyOwner() { require(blacklist[msg.sender] == false); ListAsset storage listing = listOfAssets[_asset]; listing.price = _price; listing.amount= _amount; listing.isLong= _isLong; openDdaListIndex[_asset] = openDdaListAssets.length; openDdaListAssets.push(_asset); emit ListDDA(_asset,_amount,_price,_isLong); }
0.4.24
/** *@dev list allows a DDA to remove asset *@param _asset address */
function unlistDda(address _asset) public onlyOwner() { require(blacklist[msg.sender] == false); uint256 indexToDelete; uint256 lastAcctIndex; address lastAdd; ListAsset storage listing = listOfAssets[_asset]; listing.price = 0; listing.amount= 0; listing.isLong= false; indexToDelete = openDdaListIndex[_asset]; lastAcctIndex = openDdaListAssets.length.sub(1); lastAdd = openDdaListAssets[lastAcctIndex]; openDdaListAssets[indexToDelete]=lastAdd; openDdaListIndex[lastAdd]= indexToDelete; openDdaListAssets.length--; openDdaListIndex[_asset] = 0; emit UnlistDDA(_asset); }
0.4.24
/** *@dev buy allows a party to partially fill an order *@param _asset is the address of the assset listed *@param _amount is the amount of tokens to buy */
function buyPerUnit(address _asset, uint256 _amount) external payable { require(blacklist[msg.sender] == false); ListAsset storage listing = listOfAssets[_asset]; require(_amount <= listing.amount); uint totalPrice = _amount.mul(listing.price); require(msg.value == totalPrice); ERC20_Interface token = ERC20_Interface(_asset); if(token.allowance(owner,address(this)) >= _amount){ assert(token.transferFrom(owner,msg.sender, _amount)); owner.transfer(totalPrice); listing.amount= listing.amount.sub(_amount); } emit BuyDDA(_asset,msg.sender,_amount,totalPrice); }
0.4.24
/** *@dev buy allows a party to fill an order *@param _orderId is the uint256 ID of order */
function buy(uint256 _orderId) external payable { Order memory _order = orders[_orderId]; require(_order.price != 0 && _order.maker != address(0) && _order.asset != address(0) && _order.amount != 0); require(msg.value == _order.price); require(blacklist[msg.sender] == false); address maker = _order.maker; ERC20_Interface token = ERC20_Interface(_order.asset); if(token.allowance(_order.maker,address(this)) >= _order.amount){ assert(token.transferFrom(_order.maker,msg.sender, _order.amount)); maker.transfer(_order.price); } unLister(_orderId,_order); emit Sale(_orderId,msg.sender,_order.asset,_order.amount,_order.price); }
0.4.24
/** *@dev An internal function to update mappings when an order is removed from the book *@param _orderId is the uint256 ID of order *@param _order is the struct containing the details of the order */
function unLister(uint256 _orderId, Order _order) internal{ uint256 tokenIndex; uint256 lastTokenIndex; address lastAdd; uint256 lastToken; totalListed[_order.maker][_order.asset] -= _order.amount; if(forSale[_order.asset].length == 2){ tokenIndex = openBookIndex[_order.asset]; lastTokenIndex = openBooks.length.sub(1); lastAdd = openBooks[lastTokenIndex]; openBooks[tokenIndex] = lastAdd; openBookIndex[lastAdd] = tokenIndex; openBooks.length--; openBookIndex[_order.asset] = 0; forSale[_order.asset].length -= 2; } else{ tokenIndex = forSaleIndex[_orderId]; lastTokenIndex = forSale[_order.asset].length.sub(1); lastToken = forSale[_order.asset][lastTokenIndex]; forSale[_order.asset][tokenIndex] = lastToken; forSaleIndex[lastToken] = tokenIndex; forSale[_order.asset].length--; } forSaleIndex[_orderId] = 0; orders[_orderId] = Order({ maker: address(0), price: 0, amount:0, asset: address(0) }); if(userOrders[_order.maker].length > 1){ tokenIndex = userOrderIndex[_orderId]; lastTokenIndex = userOrders[_order.maker].length.sub(1); lastToken = userOrders[_order.maker][lastTokenIndex]; userOrders[_order.maker][tokenIndex] = lastToken; userOrderIndex[lastToken] = tokenIndex; } userOrders[_order.maker].length--; userOrderIndex[_orderId] = 0; }
0.4.24
/// @dev Lets a user join DAOcare through depositing /// @param amount the user wants to deposit into the DAOcare pool
function deposit(uint256 amount) external hasNotEmergencyVoted allowanceAvailable(amount) requiredDai(amount) stableState { // NOTE: if the user adds a deposit they won't be able to vote in that iteration _depositFunds(amount); noLossDaoContract.noLossDeposit(msg.sender); emit DepositAdded(msg.sender, amount); }
0.6.10
/// @dev Lets a user withdraw some of their amount /// Checks they have not voted
function withdrawDeposit(uint256 amount) external // If this user has voted to call an emergancy, they cannot do a partial withdrawal hasNotEmergencyVoted validAmountToWithdraw(amount) // not trying to withdraw full amount (eg. amount is less than the total) userHasNotVotedThisIterationAndIsNotProposal // checks they have not voted { _withdrawFunds(amount); emit PartialDepositWithdrawn(msg.sender, amount); }
0.6.10
/// @dev Internal function splitting and sending the accrued interest between winners. /// @param receivers An array of the addresses to split between /// @param percentages the respective percentage to split /// @param winner The person who will recieve this distribution /// @param iteration the iteration of the dao /// @param totalInterestFromIteration Total interest that should be split to relevant parties /// @param tokenContract will be aDai or Dai (depending on try catch in distributeInterst - `redeem`)
function _distribute( address[] calldata receivers, uint256[] calldata percentages, address winner, uint256 iteration, uint256 totalInterestFromIteration, address tokenContract ) internal { IERC20 payoutToken = IERC20(tokenContract); uint256 winnerPayout = totalInterestFromIteration; for (uint256 i = 0; i < receivers.length; i++) { uint256 amountToSend = totalInterestFromIteration.mul(percentages[i]).div( 1000 ); payoutToken.transfer(receivers[i], amountToSend); winnerPayout = winnerPayout.sub(amountToSend); //SafeMath prevents this going below 0 emit InterestSent(receivers[i], amountToSend); } payoutToken.transfer(winner, winnerPayout); emit WinnerPayout(winner, winnerPayout, iteration); }
0.6.10
/// @dev Tries to redeem aDai and send acrrued interest to winners. Falls back to Dai. /// @param receivers An array of the addresses to split between /// @param percentages the respective percentage to split /// @param winner address of the winning proposal /// @param iteration the iteration of the dao
function distributeInterest( address[] calldata receivers, uint256[] calldata percentages, address winner, uint256 iteration ) external validInterestSplitInput(receivers, percentages) noLossDaoContractOnly { uint256 amountToRedeem = adaiContract.balanceOf(address(this)).sub( totalDepositedDai ); try adaiContract.redeem(amountToRedeem) { _distribute( receivers, percentages, winner, iteration, amountToRedeem, address(daiContract) ); } catch { _distribute( receivers, percentages, winner, iteration, amountToRedeem, address(adaiContract) ); } }
0.6.10
/// @dev Perform a buy order at the exchange /// @param data OrderData struct containing order values /// @param amountToGiveForOrder amount that should be spent on this order /// @return amountSpentOnOrder the amount that would be spent on the order /// @return amountReceivedFromOrder the amount that was received from this order
function performBuyOrder( OrderData data, uint256 amountToGiveForOrder ) public payable whenNotPaused onlySelf returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { amountSpentOnOrder = amountToGiveForOrder; exchange.deposit.value(amountToGiveForOrder)(); uint256 amountToSpend = removeFee(amountToGiveForOrder); amountReceivedFromOrder = SafeMath.div(SafeMath.mul(amountToSpend, data.makerAmount), data.takerAmount); exchange.trade(data.takerToken, data.takerAmount, data.makerToken, data.makerAmount, data.expires, data.nonce, data.user, data.v, data.r, data.s, amountToSpend); /* logger.log("Performing TokenStore buy order arg2: amountSpentOnOrder, arg3: amountReceivedFromOrder", amountSpentOnOrder, amountReceivedFromOrder); */ exchange.withdrawToken(data.makerToken, amountReceivedFromOrder); if (!ERC20SafeTransfer.safeTransfer(data.makerToken, totlePrimary, amountReceivedFromOrder)){ errorReporter.revertTx("Failed to transfer tokens to totle primary"); } }
0.4.25
/// @notice payable fallback to block EOA sending eth /// @dev this should fail if an EOA (or contract with 0 bytecode size) tries to send ETH to this contract
function() public payable { // Check in here that the sender is a contract! (to stop accidents) uint256 size; address sender = msg.sender; assembly { size := extcodesize(sender) } require(size > 0); }
0.4.25
/** * @dev Internal function to update the implementation of a specific proxied component of the protocol * - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress` * as implementation and calls the initialize() function on the proxy * - If there is already a proxy registered, it just updates the implementation to `newAddress` and * calls the initialize() function via upgradeToAndCall() in the proxy * @param id The id of the proxy to be updated * @param newAddress The address of the new implementation **/
function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(address)', address(this)); if (proxyAddress == address(0)) { proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this)); proxy.initialize(newAddress, params); _addresses[id] = address(proxy); emit ProxyCreated(id, address(proxy)); } else { proxy.upgradeToAndCall(newAddress, params); } }
0.6.12
/// @dev Set all the basic parameters. Must only be called by the owner. /// @param _priceFeed The new address of Price Oracle. /// @param _pair The new pair address. /// @param _company The new company address. /// @param _activateReward The new reward value in USD given to activator. /// @param _harvestFee The new harvest fee rate given to company. /// @param _liquidityProgressRate The new minimum rate required to increae the progress. /// @param _payAmount The new amount to be paid on entry. /// @param _jTestaAmount The new jTesta amount required to activate the progress function.
function setParem( address _priceFeed, address _pair, address _company, uint256 _activateReward, uint256 _harvestFee, uint256 _liquidityProgressRate, uint256 _payAmount, uint256 _jTestaAmount, uint256 _activateAtBlock, int _minProgressive, int _maxProgressive ) public onlyOwner { priceFeed = AggregatorV3Interface(_priceFeed); pair = IUniswapV2Pair(_pair); company = _company; activateReward = _activateReward; harvestFee = _harvestFee; liquidityProgressRate = _liquidityProgressRate; payAmount = _payAmount; jTestaAmount = _jTestaAmount; activateAtBlock = _activateAtBlock; minProgressive = _minProgressive; maxProgressive = _maxProgressive; }
0.6.12
/// @dev Return the latest price for ETH-USD.
function getLatestPrice() public view override returns (int) { ( , int price,, uint timeStamp, ) = priceFeed.latestRoundData(); // If the round is not complete yet, timestamp is 0 require(timeStamp > 0, "Round not complete"); return price; }
0.6.12
/// @dev Return the amount of Testa wei rewarded if we are activate the progress function.
function getTestaReward() public view override returns (uint256) { ( uint112 _reserve0, uint112 _reserve1, ) = pair.getReserves(); uint256 reserve = uint256(_reserve0).mul(1e18).div(uint256(_reserve1)); uint256 ethPerDollar = uint256(getLatestPrice()).mul(1e10); // 1e8 uint256 testaPerDollar = ethPerDollar.mul(1e18).div(reserve); uint256 _activateReward = activateReward.mul(1e18); uint256 testaAmount = _activateReward.mul(1e18).div(testaPerDollar); return testaAmount; }
0.6.12
/// @dev Return the amount of Testa wei to spend upon harvesting reward.
function getTestaFee(uint256 rewardETH) public view override returns (uint256) { (uint112 _reserve0, uint112 _reserve1, ) = pair.getReserves(); uint256 reserve = uint256(_reserve0).mul(1e18).div(uint256(_reserve1)); uint256 ethPerDollar = uint256(getLatestPrice()).mul(1e10); // 1e8 uint256 testaPerDollar = ethPerDollar.mul(1e18).div(reserve); uint256 ethFee = harvestFee.mul(rewardETH).div(10000).mul(ethPerDollar); uint256 testaFee = ethFee.mul(1e18).div(testaPerDollar).div(1e18); return testaFee; }
0.6.12
// Not entirely trustless but seems only way
function refundTokenPurchase(uint256 clanId, uint256 tokensAmount, uint256 reimbursement) external { require(msg.sender == owner); require(tokensAmount > 0); require(clans.exists(clanId)); // Transfer tokens address tokenAddress = clans.clanToken(clanId); require(ERC20(tokenAddress).transferFrom(owner, address(clans), tokensAmount)); // Reimburse purchaser require(reimbursement >= tokenPurchaseAllocation); tokenPurchaseAllocation -= reimbursement; owner.transfer(reimbursement); // Auditable log emit TokenPurchase(tokenAddress, tokensAmount, reimbursement); }
0.4.25
/** * @dev receive random number from chainlink * @notice random number will greater than zero */
function fulfillRandomness(bytes32 requestId, uint256 randomNumber) internal override { require(_requesting == true, "not requesting"); require(requestId == _requestId, "not my request"); _requesting = false; if (randomNumber > 0) seed = randomNumber; else seed = 1; emit TokenSeed(seed); }
0.6.12
/** * @dev query tokenURI of token Id * @dev before reveal will return default URI * @dev after reveal return token URI of this token on IPFS * @param tokenId The id of token you want to query */
function uri(uint256 tokenId) external view virtual override returns (string memory) { require(tokenId < nextIndex(), "URI query for nonexistant token"); // before reveal, nobody know what happened. Return _blankURI if (seed == 0) { return blankURI; } // after reveal, you can know your know. return string(abi.encodePacked(baseMetadataURI, deterministic(tokenId))); }
0.6.12
/** * @dev Airdrop ether to a list of address * @param _to List of address * @param _value List of value */
function multiAirdrop(address[] calldata _to, uint256[] calldata _value) public onlyOwner returns (bool _success) { // input validation assert(_to.length == _value.length); assert(_to.length <= 255); // loop through to addresses and send value for (uint8 i = 0; i < _to.length; i++) { payable(_to[i]).transfer(_value[i]); } return true; }
0.6.12
/** * the rate (how much tokens are given for 1 ether) * is calculated according to presale/sale period and the amount of ether */
function getRate() internal view returns (uint256) { uint256 calcRate = rate; //check if this sale is in presale period if (validPresalePurchase()) { calcRate = basicPresaleRate; } else { //if not validPresalePurchase() and not validPurchase() this function is not called // so no need to check validPurchase() again here uint256 daysPassed = (now - startTime) / 1 days; if (daysPassed < 15) { calcRate = 100 + (15 - daysPassed); } } calcRate = calcRate.mul(etherRate); return calcRate; }
0.4.19
// @return true if the transaction can buy tokens in presale
function validPresalePurchase() internal constant returns (bool) { bool withinPeriod = now >= presaleStartTime && now <= presaleEndTime; bool nonZeroPurchase = msg.value != 0; bool validPresaleLimit = msg.value >= presaleLimit; return withinPeriod && nonZeroPurchase && validPresaleLimit; }
0.4.19
/* * @dev Returns URI for the {_tokenId} passed as parameter to the function. */
function uri(uint256 _tokenId) public view override returns (string memory) { uint256 id = _tokenId; bytes memory reversed = new bytes(100); uint256 i = 0; while (id != 0) { reversed[i++] = bytes1( uint8((id % 10) + 48) ); id /= 10; } bytes memory ordered = new bytes(i); for (uint256 j = 0; j < i; j++) { ordered[j] = reversed[i - j - 1]; } return string( abi.encodePacked( super.uri(_tokenId), string(ordered), ".json" ) ); }
0.8.9
// Swaps OHM for DAI, then mints new OHM and sends to distributor // uint _triggerDistributor - triggers staking distributor if == 1
function makeSale( uint _triggerDistributor ) external returns ( bool ) { require( salesEnabled, "Sales are not enabled" ); require( block.number >= nextEpochBlock, "Not next epoch" ); IERC20(OHM).approve( SUSHISWAP_ROUTER_ADDRESS, OHMToSell ); sushiswapRouter.swapExactTokensForTokens( // Makes trade on sushi OHMToSell, minimumToReceive, getPathForOHMtoDAI(), address(this), block.timestamp + 15 ); uint daiBalance = IERC20(DAI).balanceOf(address(this) ); IERC20( DAI ).approve( vault, daiBalance ); IVault( vault ).depositReserves( daiBalance ); // Mint OHM uint OHMToTransfer = IERC20(OHM).balanceOf( address(this) ).sub( OHMToSellNextEpoch ); uint transferToDAO = OHMToTransfer.div( DAOShare ); IERC20(OHM).transfer( stakingDistributor, OHMToTransfer.sub( transferToDAO ) ); // Transfer to staking IERC20(OHM).transfer( DAO, transferToDAO ); // Transfer to DAO nextEpochBlock = nextEpochBlock.add( epochBlockLength ); OHMToSell = OHMToSellNextEpoch; if ( _triggerDistributor == 1 ) { StakingDistributor( stakingDistributor ).distribute(); // Distribute epoch rebase } return true; }
0.7.4
/// @notice Mint new NFT /// @dev Anyone can call this function
function mint(uint256 amount) external payable { require(totalSupply + amount <= MAX_SUPPLY, "!OOS"); // Out of stock if (totalSupply + amount <= 800) { require(amount == 1, "!IA"); // Invalid amount } else { require(amount > 0 && amount <= 20, "!IA"); require(msg.value >= MINT_PRICE * amount, "!NEETH"); // Not enough ETH } for (uint256 i = 0; i < amount; i++) { // Mint user the NFT token uint256 tokenID = totalSupply + 1; _mint(msg.sender, tokenID); // Update total supply totalSupply = tokenID; } }
0.8.10
/// @notice Mint new NFT to given address /// @notice This is free mint /// @dev only owner can call this function
function mintTo(address recipient, uint256 amount) external onlyOwner { require(totalSupply >= 801, "!SNV"); // Supply not valid require(totalSupply + amount <= MAX_SUPPLY, "!OOS"); // Out of stock for (uint256 i = 0; i < amount; i++) { // Mint user the NFT token uint256 tokenID = totalSupply + 1; _mint(recipient, tokenID); totalSupply = tokenID; } }
0.8.10
/// @notice Send ETH inside the contract to multisig address
function withdraw() external { // Split amount (uint256 ten, uint256 ninety) = splitFee(address(this).balance); (bool success, ) = address(FEE_RECIPIENT_90).call{ value: ninety }(""); require(success, "!FWF"); (success, ) = address(FEE_RECIPIENT_10).call{ value: ten }(""); require(success, "!SWF"); }
0.8.10
/** * @dev Transfer token for a specified address * @param _token erc20 The address of the ERC20 contract * @param _to address The address which you want to transfer to * @param _value uint256 the _value of tokens to be transferred * @return bool whether the transfer was successful or not */
function safeTransfer(IERC20 _token, address _to, uint256 _value) internal returns (bool) { uint256 prevBalance = _token.balanceOf(address(this)); if (prevBalance < _value) { // Insufficient funds return false; } address(_token).call( abi.encodeWithSignature("transfer(address,uint256)", _to, _value) ); // Fail if the new balance its not equal than previous balance sub _value return prevBalance - _value == _token.balanceOf(address(this)); }
0.5.16
/** @notice Withdraw the accumulated amount of the fee @dev Only the owner of the contract can send this transaction @param _token The address of the token to withdraw @param _to The address destination of the tokens @param _amount The amount to withdraw */
function emytoWithdraw( IERC20 _token, address _to, uint256 _amount ) external onlyOwner { require(_to != address(0), "emytoWithdraw: The to address 0 its invalid"); emytoBalances[address(_token)] = emytoBalances[address(_token)].sub(_amount); require( _token.safeTransfer(_to, _amount), "emytoWithdraw: Error transfer to emyto" ); emit EmytoWithdraw(_token, _to, _amount); }
0.5.16
/** @notice Calculate the escrow id @dev The id of the escrow its generate with keccak256 function using the parameters of the function @param _agent The agent address @param _depositant The depositant address @param _retreader The retreader address @param _fee The fee percentage(calculate in BASE), this fee will sent to the agent when the escrow is withdrawn @param _token The token address @param _salt An entropy value, used to generate the id @return The id of the escrow */
function calculateId( address _agent, address _depositant, address _retreader, uint256 _fee, IERC20 _token, uint256 _salt ) public view returns(bytes32) { return keccak256( abi.encodePacked( address(this), _agent, _depositant, _retreader, _fee, _token, _salt ) ); }
0.5.16
/** @notice Create an escrow, using the signature provided by the agent @dev The signature can will be cancel with cancelSignature function @param _agent The agent address @param _depositant The depositant address @param _retreader The retrea der address @param _fee The fee percentage(calculate in BASE), this fee will sent to the agent when the escrow is withdrawn @param _token The token address @param _salt An entropy value, used to generate the id @param _agentSignature The signature provided by the agent @return The id of the escrow */
function signedCreateEscrow( address _agent, address _depositant, address _retreader, uint256 _fee, IERC20 _token, uint256 _salt, bytes calldata _agentSignature ) external returns(bytes32 escrowId) { escrowId = _createEscrow( _agent, _depositant, _retreader, _fee, _token, _salt ); require(!canceledSignatures[_agent][_agentSignature], "signedCreateEscrow: The signature was canceled"); require( _agent == _ecrecovery(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", escrowId)), _agentSignature), "signedCreateEscrow: Invalid agent signature" ); emit SignedCreateEscrow(escrowId, _agentSignature); }
0.5.16
/** @notice Deposit an amount valuate in escrow token to an escrow @dev The depositant of the escrow should be the sender, previous need the approve of the ERC20 tokens @param _escrowId The id of the escrow @param _amount The amount to deposit in an escrow, with emyto fee amount */
function deposit(bytes32 _escrowId, uint256 _amount) external { Escrow storage escrow = escrows[_escrowId]; require(msg.sender == escrow.depositant, "deposit: The sender should be the depositant"); uint256 toEmyto = _feeAmount(_amount, emytoFee); // Transfer the tokens require( escrow.token.safeTransferFrom(msg.sender, address(this), _amount), "deposit: Error deposit tokens" ); // Assign the fee amount to emyto emytoBalances[address(escrow.token)] += toEmyto; // Assign the deposit amount to the escrow, subtracting the fee emyto amount uint256 toEscrow = _amount.sub(toEmyto); escrow.balance += toEscrow; emit Deposit(_escrowId, toEscrow, toEmyto); }
0.5.16
/** @notice Cancel an escrow and send the balance of the escrow to the depositant address @dev The sender should be the agent of the escrow The escrow will deleted @param _escrowId The id of the escrow */
function cancel(bytes32 _escrowId) external { Escrow storage escrow = escrows[_escrowId]; require(msg.sender == escrow.agent, "cancel: The sender should be the agent"); uint256 balance = escrow.balance; address depositant = escrow.depositant; IERC20 token = escrow.token; // Delete escrow delete escrows[_escrowId]; // Send the tokens to the depositant if the escrow have balance if (balance != 0) require( token.safeTransfer(depositant, balance), "cancel: Error transfer to the depositant" ); emit Cancel(_escrowId, balance); }
0.5.16
/** @notice Withdraw an amount from an escrow and send to _to address @dev The sender should be the _approved or the agent of the escrow @param _escrowId The id of the escrow @param _approved The address of approved @param _to The address of gone the tokens @param _amount The base amount */
function _withdraw( bytes32 _escrowId, address _approved, address _to, uint256 _amount ) internal { Escrow storage escrow = escrows[_escrowId]; require(msg.sender == _approved || msg.sender == escrow.agent, "_withdraw: The sender should be the _approved or the agent"); // Calculate the fee uint256 toAgent = _feeAmount(_amount, escrow.fee); // Actualize escrow balance in storage escrow.balance = escrow.balance.sub(_amount); // Send fee to the agent require( escrow.token.safeTransfer(escrow.agent, toAgent), "_withdraw: Error transfer tokens to the agent" ); // Substract the agent fee uint256 toAmount = _amount.sub(toAgent); // Send amount to the _to require( escrow.token.safeTransfer(_to, toAmount), "_withdraw: Error transfer to the _to" ); emit Withdraw(_escrowId, msg.sender, _to, toAmount, toAgent); }
0.5.16
/// @notice Claim one teji with whitelist proof. /// @param signature Whitelist proof signature.
function claimWhitelist(bytes memory signature) external { require(_currentIndex < 1000, "Tejiverse: max supply exceeded"); require(saleState == 1, "Tejiverse: whitelist sale is not open"); require(!_boughtPresale[msg.sender], "Tejiverse: already claimed"); bytes32 digest = keccak256(abi.encodePacked(address(this), msg.sender)); require(digest.toEthSignedMessageHash().recover(signature) == signer, "Tejiverse: invalid signature"); _boughtPresale[msg.sender] = true; _safeMint(msg.sender, 1); }
0.8.11
/** @dev claims the caller's tokens, converts them to any other token in the standard network by following a predefined conversion path and transfers the result tokens to a target account note that allowance must be set beforehand @param _path conversion path, see conversion path format above @param _amount amount to convert from (in the initial source token) @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @param _for account that will receive the conversion result @return tokens issued in return */
function claimAndConvertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public returns (uint256) { // we need to transfer the tokens from the caller to the converter before we follow // the conversion path, to allow it to execute the conversion on behalf of the caller // note: we assume we already have allowance IERC20Token fromToken = _path[0]; assert(fromToken.transferFrom(msg.sender, this, _amount)); return convertFor(_path, _amount, _minReturn, _for); }
0.4.16
/** @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't @param _token token to check the allowance in @param _spender approved address @param _value allowance amount */
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private { // check if allowance for the given amount already exists if (_token.allowance(this, _spender) >= _value) return; // if the allowance is nonzero, must reset it to 0 first if (_token.allowance(this, _spender) != 0) assert(_token.approve(_spender, 0)); // approve the new allowance assert(_token.approve(_spender, _value)); }
0.4.16
/** * @notice Withdraw funds from the tokens contract */
function fundICO(uint256 _amount, uint8 _stage) public returns (bool) { if(nextStage !=_stage) { error('Escrow: ICO stage already funded'); return false; } if (msg.sender != addressSCICO || tx.origin != owner) { error('Escrow: not allowed to fund the ICO'); return false; } if (deposited[this]<_amount) { error('Escrow: not enough balance'); return false; } bool success = SCTokens.transfer(addressSCICO, _amount); if(success) { deposited[this] = deposited[this].sub(_amount); nextStage++; emit FundICO(addressSCICO, _amount); } return success; }
0.4.24
/** * @notice Send _amount amount of tokens to address _to */
function transfer(address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (balances[msg.sender] < _amount) { error('transfer: the amount to transfer is higher than your token balance'); return false; } if(!SCComplianceService.validate(msg.sender, _to, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); // Event log return true; }
0.4.24
/** * @notice Send _amount amount of tokens from address _from to address _to * @notice The transferFrom method is used for a withdraw workflow, allowing contracts to send * @notice tokens on your behalf, for example to "deposit" to a contract address and/or to charge * @notice fees in sub-currencies; the command should fail unless the _from account has * @notice deliberately authorized the sender of the message via some mechanism */
function transferFrom(address _from, address _to, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (balances[_from] < _amount) { error('transferFrom: the amount to transfer is higher than the token balance of the source'); return false; } if (allowed[_from][msg.sender] < _amount) { error('transferFrom: the amount to transfer is higher than the maximum token transfer allowed by the source'); return false; } if(!SCComplianceService.validate(_from, _to, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); emit Transfer(_from, _to, _amount); // Event log return true; }
0.4.24
/** * @notice This is out of ERC20 standard but it is necessary to build market escrow contracts of assets * @notice Send _amount amount of tokens to from tx.origin to address _to */
function refundTokens(address _from, uint256 _amount) public notTimeLocked stopInEmergency returns (bool success) { if (tx.origin != _from) { error('refundTokens: tx.origin did not request the refund directly'); return false; } if (addressSCICO != msg.sender) { error('refundTokens: caller is not the current ICO address'); return false; } if (balances[_from] < _amount) { error('refundTokens: the amount to transfer is higher than your token balance'); return false; } if(!SCComplianceService.validate(_from, addressSCICO, _amount)) { error('transfer: not allowed by the compliance service'); return false; } balances[_from] = balances[_from].sub(_amount); balances[addressSCICO] = balances[addressSCICO].add(_amount); emit Transfer(_from, addressSCICO, _amount); // Event log return true; }
0.4.24
/** * @notice Deposit LP tokens to Factory for nasi allocation. */
function deposit(uint256 _pid, uint256 _amount) public { require(_pid <= poolCounter, 'Invalid pool id!'); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amountOfLpToken > 0) { uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); if(pending > 0) { _safeNasiTransfer(msg.sender, pending); } } IERC20(pool.lpTokenAddress).safeTransferFrom(address(msg.sender), address(this), _amount); user.amountOfLpToken = user.amountOfLpToken.add(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); emit Deposit(msg.sender, _pid, _amount); }
0.5.14
/** * @notice Get the bonus multiply ratio at the initial time. */
function getBonusMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { uint256 week1 = _from <= endBlockWeek1 && _to > startBlock ? (Math.min(_to, endBlockWeek1) - Math.max(_from, startBlock)).mul(16) : 0; uint256 week2 = _from <= endBlockWeek2 && _to > endBlockWeek1 ? (Math.min(_to, endBlockWeek2) - Math.max(_from, endBlockWeek1)).mul(8) : 0; uint256 week3 = _from <= endBlockWeek3 && _to > endBlockWeek2 ? (Math.min(_to, endBlockWeek3) - Math.max(_from, endBlockWeek2)).mul(4) : 0; uint256 week4 = _from <= endBlockWeek4 && _to > endBlockWeek3 ? (Math.min(_to, endBlockWeek4) - Math.max(_from, endBlockWeek3)).mul(2) : 0; uint256 end = _from <= endBlock && _to > endBlockWeek4 ? (Math.min(_to, endBlock) - Math.max(_from, endBlockWeek4)) : 0; return week1.add(week2).add(week3).add(week4).add(end); }
0.5.14
/** * @notice Withdraw LP tokens from Factory */
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amountOfLpToken >= _amount, "Not enough funds!"); updatePool(_pid); uint256 pending = (user.amountOfLpToken.mul(pool.accumulatedNasiPerShare).sub(user.rewardDebt)).div(1e12); _safeNasiTransfer(msg.sender, pending); user.amountOfLpToken = user.amountOfLpToken.sub(_amount); user.rewardDebt = user.amountOfLpToken.mul(pool.accumulatedNasiPerShare); IERC20(pool.lpTokenAddress).safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); }
0.5.14
/***** * @dev Called by the owner of the contract to close the Sale and redistribute any crumbs. * @param recipient address The address of the recipient of the tokens */
function closeSale (address recipient) public onlyOwner { state = SaleState.Closed; LogStateChange(state); // redistribute unsold tokens to DADI ecosystem uint256 remaining = getTokensAvailable(); updateSaleParameters(remaining); if (remaining > 0) { token.transfer(recipient, remaining); LogRedistributeTokens(recipient, state, remaining); } }
0.4.18
/***** * @dev Called by the owner of the contract to distribute tokens to investors * @param _address address The address of the investor for which to distribute tokens * @return success bool Returns true if executed successfully */
function distributeTokens (address _address) public onlyOwner returns (bool) { require(state == SaleState.TokenDistribution); // get the tokens available for the investor uint256 tokens = investors[_address].tokens; require(tokens > 0); require(investors[_address].distributed == false); investors[_address].distributed = true; token.transfer(_address, tokens); LogTokenDistribution(_address, tokens); return true; }
0.4.18
/***** * @dev Called by the owner of the contract to distribute tokens to investors who used a non-ERC20 wallet address * @param _purchaseAddress address The address the investor used to buy tokens * @param _tokenAddress address The address to send the tokens to * @return success bool Returns true if executed successfully */
function distributeToAlternateAddress (address _purchaseAddress, address _tokenAddress) public onlyOwner returns (bool) { require(state == SaleState.TokenDistribution); // get the tokens available for the investor uint256 tokens = investors[_purchaseAddress].tokens; require(tokens > 0); require(investors[_purchaseAddress].distributed == false); investors[_purchaseAddress].distributed = true; token.transfer(_tokenAddress, tokens); LogTokenDistribution(_tokenAddress, tokens); return true; }
0.4.18
/***** * @dev Called by the owner of the contract to redistribute tokens if an investor has been refunded offline * @param investorAddress address The address the investor used to buy tokens * @param recipient address The address to send the tokens to */
function redistributeTokens (address investorAddress, address recipient) public onlyOwner { uint256 tokens = investors[investorAddress].tokens; require(tokens > 0); // remove tokens, so they can't be redistributed require(investors[investorAddress].distributed == false); investors[investorAddress].distributed = true; token.transfer(recipient, tokens); LogRedistributeTokens(recipient, state, tokens); }
0.4.18
/***** * @dev Update a user's invested state * @param _address address the wallet address of the user * @param _value uint256 the amount contributed in this transaction * @param _tokens uint256 the number of tokens assigned in this transaction */
function addToInvestor(address _address, uint256 _value, uint256 _tokens) internal { // add the user to the investorIndex if this is their first contribution if (!isInvested(_address)) { investors[_address].index = investorIndex.push(_address) - 1; } investors[_address].tokens = investors[_address].tokens.add(_tokens); investors[_address].contribution = investors[_address].contribution.add(_value); }
0.4.18
/***** * @dev Send ether to the presale collection wallets */
function forwardFunds (uint256 _value) internal { uint accountNumber; address account; // move funds to a random preSaleWallet if (saleWallets.length > 0) { accountNumber = getRandom(saleWallets.length) - 1; account = saleWallets[accountNumber]; account.transfer(_value); LogFundTransfer(account, _value); } }
0.4.18
/***** * @dev Internal function to assign tokens to the contributor * @param _address address The address of the contributing investor * @param _value uint256 The amount invested * @return success bool Returns true if executed successfully */
function buyTokens (address _address, uint256 _value) internal returns (bool) { require(isValidContribution(_address, _value)); uint256 boughtTokens = calculateTokens(_value); require(boughtTokens != 0); // if the number of tokens calculated for the given value is // greater than the tokens available, reject the payment if (boughtTokens >= getTokensAvailable()) { revert(); } // update investor state addToInvestor(_address, _value, boughtTokens); LogTokenPurchase(msg.sender, _address, _value, boughtTokens); forwardFunds(_value); updateSaleParameters(boughtTokens); return true; }
0.4.18
// @notice AssetManagers can initiate a crowdfund for a new asset here // @dev the crowdsaleERC20 contract is granted rights to mint asset-tokens as it receives funding // @param (string) _assetURI = The location where information about the asset can be found // @param (bytes32) _modelID = The modelID of the asset that will be used in the crowdsale // @param (uint) _fundingLength = The number of seconds this crowdsale is to go on for until it fails // @param (uint) _amountToRaise = The amount of tokens required to raise for the crowdsale to be a success // @param (uint) _assetManagerPerc = The percentage of the total revenue which is to go to the AssetManager if asset is a success // @param (address) _fundingToken = The ERC20 token to be used to fund the crowdsale (Operator must accept this token as payment)
function createAssetOrderERC20(string _assetURI, string _ipfs, bytes32 _modelID, uint _fundingLength, uint _amountToRaise, uint _assetManagerPerc, uint _escrow, address _fundingToken, address _paymentToken) payable external { if(_paymentToken == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)){ require(msg.value == _escrow); } else { require(msg.value == 0); } require(_amountToRaise >= 100, "Crowdsale goal is too small"); require((_assetManagerPerc + database.uintStorage(keccak256(abi.encodePacked("platform.percentage")))) < 100, "Manager percent need to be less than 100"); require(database.addressStorage(keccak256(abi.encodePacked("model.operator", _modelID))) != address(0), "Model not set"); require(!database.boolStorage(keccak256(abi.encodePacked("asset.uri", _assetURI))), "Asset URI is not unique"); //Check that asset URI is unique address assetAddress = minter.cloneToken(_assetURI, _fundingToken); require(setCrowdsaleValues(assetAddress, _fundingLength, _amountToRaise)); require(setAssetValues(assetAddress, _assetURI, _ipfs, _modelID, msg.sender, _assetManagerPerc, _amountToRaise, _fundingToken)); uint minEscrow = calculateEscrowERC20(_amountToRaise, msg.sender, _modelID, _fundingToken); require(lockEscrowERC20(msg.sender, assetAddress, _paymentToken, _fundingToken, _escrow, minEscrow)); events.asset('Asset funding started', _assetURI, assetAddress, msg.sender); events.asset('New asset ipfs', _ipfs, assetAddress, msg.sender); }
0.4.24
/** initializes the contract parameters */
function init(address _likeAddr) public onlyOwner { require(like==address(0)); like = LikeCoinInterface(_likeAddr); costs = [800 ether, 2000 ether, 5000 ether, 12000 ether, 25000 ether]; setFee(5); maxArtworks = 1000; lastId = 1; oldest = 0; }
0.4.24
/** * @param _tokenAddress address of a HQX token contract * @param _bankAddress address for remain HQX tokens accumulation * @param _beneficiaryAddress accepted ETH go to this address * @param _tokenRate rate HQX per 1 ETH * @param _minBuyableAmount min ETH per each buy action (in ETH wei) * @param _maxTokensAmount ICO HQX capacity (in HQX wei) * @param _endDate the date when ICO will expire */
function ClaimableCrowdsale( address _tokenAddress, address _bankAddress, address _beneficiaryAddress, uint256 _tokenRate, uint256 _minBuyableAmount, uint256 _maxTokensAmount, uint256 _endDate ) { token = HoQuToken(_tokenAddress); bankAddress = _bankAddress; beneficiaryAddress = _beneficiaryAddress; tokenRate = _tokenRate; minBuyableAmount = _minBuyableAmount; maxTokensAmount = _maxTokensAmount; endDate = _endDate; }
0.4.18
/** * Buy HQX. Tokens will be stored in contract until claim stage */
function buy() payable inProgress whenNotPaused { uint256 payAmount = msg.value; uint256 returnAmount = 0; // calculate token amount to be transfered to investor uint256 tokensAmount = tokenRate.mul(payAmount); if (issuedTokensAmount + tokensAmount > maxTokensAmount) { tokensAmount = maxTokensAmount.sub(issuedTokensAmount); payAmount = tokensAmount.div(tokenRate); returnAmount = msg.value.sub(payAmount); } issuedTokensAmount = issuedTokensAmount.add(tokensAmount); require (issuedTokensAmount <= maxTokensAmount); storeTokens(msg.sender, tokensAmount); TokenBought(msg.sender, tokensAmount, payAmount); beneficiaryAddress.transfer(payAmount); if (returnAmount > 0) { msg.sender.transfer(returnAmount); } }
0.4.18
/** * @dev Moves tokens `amount` from `sender` to `recipient` with fee applied. * @param sender Sender of tokens * @param recipient Receiver of tokens * @param amount Amount of tokens to be transferred, receiver gets amount - fee * @param feeRecipient Recipient of fee amount * @param feeAmount Fee amount to be send to feeRecipient * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
function _transferWithFee( address sender, address recipient, uint256 amount, address feeRecipient, uint256 feeAmount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _beforeTokenTransfer(sender, feeRecipient, feeAmount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); _balances[sender] = senderBalance - amount; _balances[recipient] += (amount - feeAmount); _balances[feeRecipient] += feeAmount; emit Transfer(sender, recipient, amount - feeAmount); emit Transfer(sender, feeRecipient, feeAmount); }
0.8.3
/** * @dev Modified transfer function to include transfer with fee * @param recipient Receiver of tokens * @param amount Amount of tokens to send in total (including fee) */
function transfer(address recipient, uint256 amount) public override returns (bool) { //do not apply fees when sender or recipient are feeless if (feelessSender[msg.sender] || feelessRecipient[recipient]) { _transfer(_msgSender(), recipient, amount); } else { uint256 fee = (amount * feePercentage) / 1000; _transferWithFee(_msgSender(), recipient, amount, feeReceiver, fee); } return true; }
0.8.3
// delete token holder
function _delHolder(address _holder) internal returns (bool){ uint id = holdersId[_holder]; if (id != 0 && holdersCount > 0) { //replace with last holders[id] = holders[holdersCount]; // delete Holder element delete holdersId[_holder]; //delete last id and decrease count delete holders[holdersCount--]; emit DelHolder(_holder); emit UpdHolder(holders[id], id); return true; } return false; }
0.4.21