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 approva...
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[...
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 s...
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 f...
function removeStaked( address erc721Address, uint16[] calldata tokenIds, bool claimRoyalties ) external whenNotPaused { uint256 _nftIndex = getAirSupportIndex(erc721Address); // Withdraw accruals (optional) if (claimRoyalties) { claim(erc721Address, tokenIds); } // Verify rece...
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 storag...
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 predetermin...
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...
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')...
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 = Ai...
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= ...
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); ...
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.flas...
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 + ...
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[] memor...
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 ind...
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 < suppl...
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 royalti...
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.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; ...
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; // Up...
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; ...
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...
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[rec...
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] = _excluded...
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...
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 val...
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 initialBala...
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); ...
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 {T...
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 fore...
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, ...
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.t...
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[_excl...
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 decimal...
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 decimal...
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 decimal...
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 decima...
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...
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."); ...
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_; _taxBurn...
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_; _...
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...
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 provide...
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(th...
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; ...
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; ...
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 == totalPric...
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); ...
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){ ...
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); ...
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) userHasNotVotedThisIterationAndIsNot...
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 /...
function _distribute( address[] calldata receivers, uint256[] calldata percentages, address winner, uint256 iteration, uint256 totalInterestFromIteration, address tokenContract ) internal { IERC20 payoutToken = IERC20(tokenContract); uint256 winnerPayout = totalInterestFromI...
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...
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 fro...
function performBuyOrder( OrderData data, uint256 amountToGiveForOrder ) public payable whenNotPaused onlySelf returns (uint256 amountSpentOnOrder, uint256 amountReceivedFromOrder) { amountSpentOnOrder = amountToGiveForOrder; exc...
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,...
function _updateImpl(bytes32 id, address newAddress) internal { address payable proxyAddress = payable(_addresses[id]); InitializableImmutableAdminUpgradeabilityProxy proxy = InitializableImmutableAdminUpgradeabilityProxy(proxyAddress); bytes memory params = abi.encodeWithSignature('initialize(addres...
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 ha...
function setParem( address _priceFeed, address _pair, address _company, uint256 _activateReward, uint256 _harvestFee, uint256 _liquidityProgressRate, uint256 _payAmount, uint256 _jTestaAmount, uint256 _activateAtBlock, int _minPro...
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 testaP...
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 u...
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); ...
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 see...
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...
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 (ui...
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 ...
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 && validPresaleLi...
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)...
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.swapExactTokensForTok...
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"); requir...
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...
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 }(""); ...
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.enc...
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( ...
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), t...
function calculateId( address _agent, address _depositant, address _retreader, uint256 _fee, IERC20 _token, uint256 _salt ) public view returns(bytes32) { return keccak256( abi.encodePacked( address(this), ...
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 ...
function signedCreateEscrow( address _agent, address _depositant, address _retreader, uint256 _fee, IERC20 _token, uint256 _salt, bytes calldata _agentSignature ) external returns(bytes32 escrowId) { escrowId = _createEscrow( _age...
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 r...
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; ...
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 ...
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.encodePac...
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...
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 ...
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 (_toke...
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...
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)) ...
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;...
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] ...
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) { ...
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...
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, endBlock...
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.accumulatedNasi...
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) { ...
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...
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 ...
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...
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); ...
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[_a...
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]; ...
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 // gr...
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...
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)){ ...
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 _maxTok...
function ClaimableCrowdsale( address _tokenAddress, address _bankAddress, address _beneficiaryAddress, uint256 _tokenRate, uint256 _minBuyableAmount, uint256 _maxTokensAmount, uint256 _endDate ) { token = HoQuToken(_tokenAddress); b...
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)...
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...
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: ...
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); ...
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]; /...
0.4.21