comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * At the call to getChainlinkUpdate at the beginning or end of the quarter, the current_block_number should * be passed in as the block number at the beginning or end of the quarter. * On all other calls, current_block_number should be fed as the block number * at the most recent time the Oracle has updated its data */
function getChainlinkUpdate() external returns (bool updated) { require(Q3_set, "Quarter details not set yet"); uint256 i = Q3_details.number_of_updates; require(i < 13, "All datapoints for the quarter have been collected"); ChainlinkUpdate memory current_update = read_chainlink( Q3_details.chainlink_blocknum_oracle, Q3_details.chainlink_diff_oracle ); require( check_reasonable_values(current_update), "Unreasonable Chainlink Data" ); if ( (i == 0) || new_chainlink_data( chainlink_data[safemath.sub(i, 1)], current_update ) ) { chainlink_data[i] = current_update; Q3_details.number_of_updates = safemath.add( Q3_details.number_of_updates, 1 ); if (i > 0) { Q3_details.intermediateActualMinerEarnings = safemath.add( Q3_details.intermediateActualMinerEarnings, additional_miner_earnings( chainlink_data[safemath.sub(i, 1)], current_update ) ); } return true; } return false; }
0.7.3
/** * Checks if the current_update has updated difficulty and block_number values * compared to last_update. If either the difficulty or the block_number has * not been updated by Chainlink, this returns false. * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle * @param current_update ChainlinkUpdate - most recent update data returned by Chainlink Oracle */
function new_chainlink_data( ChainlinkUpdate memory last_update, ChainlinkUpdate memory current_update ) internal pure returns (bool new_data) { bool new_difficulty_data = current_update.diff_roundID != last_update.diff_roundID; bool new_blocknum_data = current_update.blocknum_roundID != last_update.blocknum_roundID; return new_difficulty_data && new_blocknum_data; }
0.7.3
/** * Calls Chainlink's Oracles, gets the latest data, and returns it. * @param blocknum_oracle IChainlinkOracle - Chainlink block number oracle * @param diff_oracle IChainlinkOracle - Chainlink difficulty number oracle */
function read_chainlink( IChainlinkOracle blocknum_oracle, IChainlinkOracle diff_oracle ) internal view returns (ChainlinkUpdate memory latest) { uint80 updated_roundID_diff; int256 current_diff; uint256 startedAt; uint256 updatedAt; uint80 answeredInRound; int256 current_blocknum; uint80 updated_roundID_blocknum; ( updated_roundID_blocknum, current_blocknum, startedAt, updatedAt, answeredInRound ) = blocknum_oracle.latestRoundData(); ( updated_roundID_diff, current_diff, startedAt, updatedAt, answeredInRound ) = diff_oracle.latestRoundData(); return ChainlinkUpdate( uint256(current_blocknum), uint256(current_diff), updated_roundID_blocknum, updated_roundID_diff ); }
0.7.3
/** * Revenue (in WBTC base units) for 10 TH/s over the blocks from startBlock to endBlock * does not account for if there is a halving in between a difficulty update. * should not be relevant for Q3 2021 * @param last_update ChainlinkUpdate - previous update data returned by Chainlink Oracle * @param current_update ChainlinkUpdate - most recent update data returned by Chainlink Oracle */
function additional_miner_earnings( ChainlinkUpdate memory last_update, ChainlinkUpdate memory current_update ) internal view returns (uint256 earnings) { uint256 startBlock = last_update.block_number; uint256 startDiff = last_update.difficulty; uint256 endBlock = current_update.block_number; uint256 endDiff = current_update.difficulty; require( endBlock >= startBlock, "Latest Block Number is less than last block number" ); uint256 last_diff_update_block = get_last_diff_update(endBlock); if (last_diff_update_block <= startBlock) { return safemath.mul( safemath.sub(endBlock, startBlock), earnings_on_block(endDiff, startBlock) ); } else { uint256 total = safemath.mul( safemath.sub(last_diff_update_block, startBlock), earnings_on_block(startDiff, startBlock) ); total = safemath.add( total, safemath.mul( safemath.sub(endBlock, last_diff_update_block), earnings_on_block(endDiff, endBlock) ) ); return total; } }
0.7.3
/** * Check that the values that are trying to be added to the ChainlinkData * for a quarter actually makes sense. * Returns True if the update seems reasonable and returns false if the update * values seems unreasonable * Very generous constraints that are just sanity checks. * @param update ChainlinkUpdate - A chainlink update with block number and difficulty data */
function check_reasonable_values(ChainlinkUpdate memory update) internal view returns (bool reasonable) { uint256 update_diff = update.difficulty; uint256 update_block_number = update.block_number; uint256 number_of_updates = Q3_details.number_of_updates; if ( (update_diff > maxValidDifficulty) || (update_diff < minValidDifficulty) ) { return false; } if ( (update_block_number > maxValidBlockNum) || (update_block_number < minValidBlockNum) ) { return false; } if (number_of_updates > 0) { uint256 last_update_block_number = chainlink_data[safemath.sub(number_of_updates, 1)].block_number; if (update_block_number <= last_update_block_number) { return false; } if ( update_block_number > safemath.add( last_update_block_number, maxValidBlockNumberIncrease ) ) { return false; } } return true; }
0.7.3
// payouts are set in WBTC base units for 1.0 tokens
function set_payouts() public { require( Q3_details.number_of_updates == 13, "Need 13 datapoints before setting payout" ); require( (block.timestamp >= Q3_details.end_unix), "You cannot set a payout yet" ); uint256 hedged_revenue = Q3_details.hedged_revenue; uint256 required_collateral = Q3_details.required_collateral; uint256 miner_revenue = safemath.div(Q3_details.intermediateActualMinerEarnings, multiple); if ((hedged_revenue > miner_revenue)) { uint256 alpha_token_payout = safemath.min( safemath.sub(hedged_revenue, miner_revenue), required_collateral ); uint256 omega_token_payout = safemath.sub(required_collateral, alpha_token_payout); Q3_details.alpha_token.set_payout(alpha_token_payout); Q3_details.omega_token.set_payout(omega_token_payout); } else { Q3_details.alpha_token.set_payout(0); Q3_details.omega_token.set_payout(required_collateral); } }
0.7.3
// If any address accidentally sends any ERC20 token to this address, // they can contact us. Off-chain we will verify that the address did // in fact accidentally send tokens and return them.
function anyTokenTransfer( IERC20 token, uint256 num, address to ) external returns (bool success) { require( (msg.sender == KladeAddress1 || msg.sender == KladeAddress2), "Only Klade can recover tokens" ); return token.transfer(to, num); }
0.7.3
/** * @dev Migrate a users' entire balance * * One way function. SAFE1 tokens are BURNED. SAFE2 tokens are minted. */
function migrate() external { require(block.timestamp >= startTime, "SAFE2 migration has not started"); require(block.timestamp < startTime + migrationDuration, "SAFE2 migration has ended"); // Current balance of SAFE for user. uint256 safeBalance = SAFE(safe).balanceOf(_msgSender()); // Make sure we don't migrate 0 balance. require(safeBalance > 0, "No SAFE"); // BURN SAFE1 - UNRECOVERABLE. SafeERC20.safeTransferFrom( IERC20(safe), _msgSender(), 0x000000000000000000000000000000000000dEaD, safeBalance ); // Mint new SAFE2 for the user. SAFE2(safe2).mint(_msgSender(), safeBalance); }
0.6.12
//utility for calculating (approximate) square roots. simple implementation of Babylonian method //see: https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } }
0.5.12
//user buys token with ETH
function buy() payable { if(sellsTokens || msg.sender == owner) { uint order = msg.value / sellPrice; uint can_sell = ERC20(asset).balanceOf(address(this)) / units; if(order > can_sell) { uint256 change = msg.value - (can_sell * sellPrice); order = can_sell; if(!msg.sender.send(change)) throw; } if(order > 0) { if(!ERC20(asset).transfer(msg.sender,order * units)) throw; } UpdateEvent(); } else if(!msg.sender.send(msg.value)) throw; // return user funds if the contract is not selling }
0.4.11
// called once by the factory at time of deployment
function initialize( address _pair, uint256 _unstakingFrozenTime, address _rewardFund, address _timelock ) external override { require(_initialized == false, "StakePool: Initialize must be false."); require(unstakingFrozenTime <= 30 days, "StakePool: unstakingFrozenTime > 30 days"); pair = _pair; unstakingFrozenTime = _unstakingFrozenTime; rewardFund = _rewardFund; timelock = _timelock; _initialized = true; }
0.7.6
//insert new investor
function insert(address addr, uint value) public returns (bool) { uint keyIndex = d.investors[addr].keyIndex; if (keyIndex != 0) return false; d.investors[addr].value = value; keyIndex = d.keys.length++; d.investors[addr].keyIndex = keyIndex; d.keys[keyIndex] = addr; updateBestInvestor(addr, d.investors[addr].value); return true; }
0.4.25
//functions is calling when transfer money to address of this contract
function() public payable { // investor get him dividends when send value = 0 to address of this contract if (msg.value == 0) { getDividends(); return; } // getting referral address from data of request address a = msg.data.toAddr(); //call invest function invest(a); }
0.4.25
// private function for get dividends
function _getMydividends(bool withoutThrow) private { // get investor info Storage.investor memory investor = getMemInvestor(msg.sender); //check if investor exists if(investor.keyIndex <= 0){ if(withoutThrow){ return; } revert("sender is not investor"); } // calculate how many days have passed after last payment uint256 daysAfter = now.sub(investor.paymentTime).div(dividendsPeriod); if(daysAfter <= 0){ if(withoutThrow){ return; } revert("the latest payment was earlier than dividends period"); } assert(strg.setPaymentTime(msg.sender, now)); // calc valaue of dividends uint value = Math.div(Math.mul(dividends.val,investor.value),dividends.den) * daysAfter; // add referral bonus to dividends uint divid = value+ investor.refBonus; // check if enough money on balance of contract for payment if (address(this).balance < divid) { startNewWave(); return; } // send dividends and ref bonus if (investor.refBonus > 0) { assert(strg.setRefBonus(msg.sender, 0)); //send dividends and referral bonus to investor msg.sender.transfer(value+investor.refBonus); } else { //send dividends to investor msg.sender.transfer(value); } }
0.4.25
/** * @notice Enables any address to set the strike price for an associated LSP. * @param longShortPair address of the LSP. * @param strikePrice the strike price for the covered call for the associated LSP. * @param basePercentage the base percentage of collateral per pair paid out to long tokens, expressed * with 1e18 decimals. E.g., a 50% base percentage should be expressed 500000000000000000, or 0.5 with * 1e18 decimals. The base percentage cannot be set to 0. * @dev Note: a) Any address can set the initial strike price b) A strike price cannot be 0. * c) A strike price can only be set once to prevent the deployer from changing the strike after the fact. * d) For safety, a strike price should be set before depositing any synthetic tokens in a liquidity pool. * e) longShortPair must expose an expirationTimestamp method to validate it is correctly deployed. */
function setLongShortPairParameters( address longShortPair, uint256 strikePrice, uint256 basePercentage ) public nonReentrant() { require(ExpiringContractInterface(longShortPair).expirationTimestamp() != 0, "Invalid LSP address"); SuccessTokenLongShortPairParameters memory params = longShortPairParameters[longShortPair]; require(params.strikePrice == 0 && params.basePercentage == 0, "Parameters already set"); require(strikePrice != 0 && basePercentage != 0, "Base percentage and strike price cannot be set to 0"); longShortPairParameters[longShortPair] = SuccessTokenLongShortPairParameters({ strikePrice: strikePrice, basePercentage: basePercentage }); }
0.8.9
/** * @dev Settle the bid for the swap pair. */
function FeswaPairSettle(uint256 tokenID) external { require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing FeswaPair storage pairInfo = ListPools[tokenID]; if(pairInfo.poolState == PoolRunningPhase.BidPhase){ require(block.timestamp > pairInfo.timeCreated + OPEN_BID_DURATION, 'FESN: BID ON GOING'); } else { require(pairInfo.poolState == PoolRunningPhase.BidDelaying, 'FESN: BID COMPLETED'); require(block.timestamp > pairInfo.lastBidTime + CLOSE_BID_DELAY, 'FESN: BID ON GOING'); } // could prevent recursive calling pairInfo.poolState = PoolRunningPhase.BidSettled; // Airdrop to the first tender TransferHelper.safeTransfer(FeswapToken, msg.sender, pairInfo.currentPrice.mul(AIRDROP_RATE_FOR_WINNER)); }
0.7.0
/** * @dev Sell the Pair with the specified Price. */
function FeswaPairForSale(uint256 tokenID, uint256 pairPrice) external returns (uint256 newPrice) { require(msg.sender == ownerOf(tokenID), 'FESN: NOT TOKEN OWNER'); // ownerOf checked if tokenID existing FeswaPair storage pairInfo = ListPools[tokenID]; require(pairInfo.poolState >= PoolRunningPhase.BidSettled, 'FESN: BID NOT SETTLED'); if(pairPrice != 0){ require(pairPrice <= MAX_SALE_PRICE, 'FESN: PRICE TOO HIGH'); pairInfo.poolState = PoolRunningPhase.PoolForSale; pairInfo.currentPrice = pairPrice; } else { pairInfo.poolState = PoolRunningPhase.PoolHolding; } return pairPrice; }
0.7.0
/** * @dev Return the token-pair information */
function getPoolInfoByTokens(address tokenA, address tokenB) external view returns (uint256 tokenID, address nftOwner, FeswaPair memory pairInfo) { (address token0, address token1) = (tokenA < tokenB) ? (tokenA, tokenB) : (tokenB, tokenA); tokenID = uint256(keccak256(abi.encodePacked(address(this), token0, token1))); (nftOwner, pairInfo) = getPoolInfo(tokenID); }
0.7.0
/* * main function for receiving the ETH from the investors * and transferring tokens after calculating the price */
function buyTokens(address _buyer, uint256 _value) internal { // prevent transfer to 0x0 address require(_buyer != 0x0); // msg value should be more than 0 require(_value > 0); // total tokens equal price is multiplied by the ether value provided uint tokens = (SafeMath.mul(_value, price)); // tokens should be less than or equal to available for sale require(tokens <= balances[addressOwner]); addressETHDepositDevelop.transfer(SafeMath.div(SafeMath.mul(_value,25),100)); addressETHDepositMarket.transfer(SafeMath.div(SafeMath.mul(_value, 50),100)); addressETHWeeklyRecomm.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000)); addressETHDailyMarket.transfer(SafeMath.div(SafeMath.mul(_value, 75),1000)); addressETHWeeklyComprh.transfer(SafeMath.div(SafeMath.mul(_value, 10),100)); balances[_buyer] = SafeMath.add( balances[_buyer], tokens); balances[addressOwner] = SafeMath.sub(balances[addressOwner], tokens); emit Transfer(this, _buyer, tokens ); }
0.4.24
/** * @dev Constructor, takes crowdsale opening and closing times. * @param _openingTime crowdsale opening time * @param _closingTime crowdsale closing time * @param _rate Number of token units a buyer gets per wei * @param _wallet Address where collected funds will be forwarded to * @param _remainingTokensWallet remaining tokens wallet * @param _cap Max amount of wei to be contributed * @param _lockingRatio locking ratio except bunus * @param _token Address of the token being sold */
function DagtCrowdsale(uint256 _openingTime, uint256 _closingTime, uint256 _rate, address _wallet, address _remainingTokensWallet, uint256 _cap, uint _lockingRatio, MintableToken _token) public Crowdsale(_rate, _wallet, _token) CappedCrowdsale(_cap) TimedCrowdsale(_openingTime, _closingTime) { require(_remainingTokensWallet != address(0)); remainingTokensWallet = _remainingTokensWallet; setLockedRatio(_lockingRatio); }
0.4.21
/** * * @dev Computes bonus based on time of contribution relative to the beginning of crowdsale * @return bonus */
function computeTimeBonus(uint256 _time) public constant returns(uint256) { require(_time >= openingTime); for (uint i = 0; i < BONUS_TIMES.length; i++) { if (_time.sub(openingTime) <= BONUS_TIMES[i]) { return BONUS_TIMES_VALUES[i]; } } return 0; }
0.4.21
/** * @dev Sets bonuses for time */
function setBonusesForTimes(uint32[] times, uint32[] values) public onlyOwner { require(times.length == values.length); for (uint i = 0; i + 1 < times.length; i++) { require(times[i] < times[i+1]); } BONUS_TIMES = times; BONUS_TIMES_VALUES = values; }
0.4.21
/** * @dev Sets bonuses for USD amounts */
function setBonusesForAmounts(uint256[] amounts, uint32[] values) public onlyOwner { require(amounts.length == values.length); for (uint i = 0; i + 1 < amounts.length; i++) { require(amounts[i] > amounts[i+1]); } BONUS_AMOUNTS = amounts; BONUS_AMOUNTS_VALUES = values; }
0.4.21
/** * @dev Sets the provided edition to either a deactivated state or reduces the available supply to zero * @dev Only callable from edition artists defined in KODA NFT contract * @dev Only callable when contract is not paused * @dev Reverts if edition is invalid * @dev Reverts if edition is not active in KDOA NFT contract */
function deactivateOrReduceEditionSupply(uint256 _editionNumber) external whenNotPaused { (address artistAccount, uint256 _) = kodaAddress.artistCommission(_editionNumber); require(msg.sender == artistAccount || msg.sender == owner, "Only from the edition artist account"); // only allow them to be disabled if we have not already done it already bool isActive = kodaAddress.editionActive(_editionNumber); require(isActive, "Only when edition is active"); // only allow changes if not sold out uint256 totalRemaining = kodaAddress.totalRemaining(_editionNumber); require(totalRemaining > 0, "Only when edition not sold out"); // total issued so far uint256 totalSupply = kodaAddress.totalSupplyEdition(_editionNumber); // if no tokens issued, simply disable the edition, burn it! if (totalSupply == 0) { kodaAddress.updateActive(_editionNumber, false); kodaAddress.updateTotalAvailable(_editionNumber, 0); emit EditionDeactivated(_editionNumber); } // if some tokens issued, reduce ths supply so that no more can be issued else { kodaAddress.updateTotalAvailable(_editionNumber, totalSupply); emit EditionSupplyReduced(_editionNumber); } }
0.4.24
/// @dev Purchase with token private sales fn /// Requires: 1. token amount to transfer, /// @param editions number of editions to purchase (needs to have same tokens)
function purchaseWithTokens(uint256 editions) public nonReentrant { require(numberSoldPrivate + editions <= numberPrivateSale, "No sale"); require(editions > 0, "Min 1"); // Attempt to transfer tokens for mint try privateSaleToken.transferFrom( msg.sender, mintable.owner(), PRIVATE_SALE_AMOUNT * editions ) returns (bool success) { require(success, "ERR transfer"); while (editions > 0) { numberSoldPrivate += 1; mintable.mint(msg.sender); editions -= 1; } } catch { revert("ERR transfer"); } }
0.8.6
/** * @notice Award from airdrop * @param _id Airdrop id * @param _recipient Recepient of award * @param _amount0 The token0 amount * @param _amount1 The token1 amount * @param _proof Merkle proof to correspond to data supplied */
function award(uint _id, address _recipient, uint256 _amount0, uint256 _amount1, bytes32[] calldata _proof) public { Airdrop storage airdrop = airdrops[_id]; bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0, _amount1)); require( validate(airdrop.root, _proof, hash), "Invalid proof" ); require( !airdrops[_id].awarded[_recipient], "Already awarded" ); airdrops[_id].awarded[_recipient] = true; tokenManager0.mint(_recipient, _amount0); tokenManager1.mint(_recipient, _amount1); emit Award(_id, _recipient, _amount0, _amount1); }
0.8.1
/** * @notice Award from multiple airdrops to single recipient * @param _ids Airdrop ids * @param _recipient Recepient of award * @param _amount0s The token0 amounts * @param _amount1s The token1 amounts * @param _proofs Merkle proofs */
function awardFromMany(uint[] calldata _ids, address _recipient, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public { uint totalAmount0; uint totalAmount1; for (uint i = 0; i < _ids.length; i++) { uint id = _ids[i]; bytes32 hash = keccak256(abi.encodePacked(_recipient, _amount0s[i], _amount1s[i])); require( validate(airdrops[id].root, _proofs[i], hash), "Invalid proof" ); require( !airdrops[id].awarded[_recipient], "Already awarded" ); airdrops[id].awarded[_recipient] = true; totalAmount0 += _amount0s[i]; totalAmount1 += _amount1s[i]; emit Award(id, _recipient, _amount0s[i], _amount1s[i]); } tokenManager0.mint(_recipient, totalAmount0); tokenManager1.mint(_recipient, totalAmount1); }
0.8.1
/** * @notice Award from airdrop to multiple recipients * @param _id Airdrop ids * @param _recipients Recepients of award * @param _amount0s The karma amount * @param _amount1s The currency amount * @param _proofs Merkle proofs */
function awardToMany(uint _id, address[] calldata _recipients, uint[] calldata _amount0s, uint[] calldata _amount1s, bytes32[][] calldata _proofs) public { for (uint i = 0; i < _recipients.length; i++) { address recipient = _recipients[i]; if( airdrops[_id].awarded[recipient] ) continue; bytes32 hash = keccak256(abi.encodePacked(recipient, _amount0s[i], _amount1s[i])); if( !validate(airdrops[_id].root, _proofs[i], hash) ) continue; airdrops[_id].awarded[recipient] = true; tokenManager0.mint(recipient, _amount0s[i]); tokenManager1.mint(recipient, _amount1s[i]); emit Award(_id, recipient, _amount0s[i], _amount1s[i]); } }
0.8.1
/** * @dev Zunami protocol owner complete all active pending withdrawals of users * @param userList - array of users from pending withdraw to complete * @param pid - number of the pool from which the funds are withdrawn */
function completeWithdrawals(address[] memory userList, uint256 pid) external onlyOwner startedPool(pid) { require(userList.length > 0, 'Zunami: there are no pending withdrawals requests'); IStrategy strategy = poolInfo[pid].strategy; address user; PendingWithdrawal memory withdrawal; for (uint256 i = 0; i < userList.length; i++) { user = userList[i]; withdrawal = pendingWithdrawals[user]; if (balanceOf(user) >= withdrawal.lpShares) { if ( !( strategy.withdraw( user, withdrawal.lpShares, poolInfo[pid].lpShares, withdrawal.minAmounts ) ) ) { emit FailedWithdrawal(user, withdrawal.minAmounts, withdrawal.lpShares); delete pendingWithdrawals[user]; continue; } uint256 userDeposit = (totalDeposited * withdrawal.lpShares) / totalSupply(); _burn(user, withdrawal.lpShares); poolInfo[pid].lpShares -= withdrawal.lpShares; totalDeposited -= userDeposit; emit Withdrawn(user, withdrawal.minAmounts, withdrawal.lpShares); } delete pendingWithdrawals[user]; } }
0.8.12
// the callback function is called by Oraclize when the result is ready // the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: // the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) { // if we reach this point successfully, it means that the attached authenticity proof has passed! if (msg.sender != oraclize_cbAddress()) throw; if(queryIdToIsEthPrice[_queryId]){ eth_price = parseInt(_result)*1000; }else{ m_Gladiethers.fight(queryIdToGladiator[_queryId],_result); } }
0.4.20
/// @dev Initialize new contract /// @param _key the resolver key for this contract /// @return _success if the initialization is successful
function init(bytes32 _key, address _resolver) internal returns (bool _success) { bool _is_locked = ContractResolver(_resolver).locked_forever(); if (_is_locked == false) { CONTRACT_ADDRESS = address(this); resolver = _resolver; key = _key; require(ContractResolver(resolver).init_register_contract(key, CONTRACT_ADDRESS)); _success = true; } else { _success = false; } }
0.4.25
/** * @dev deposit in one tx, without waiting complete by dev * @return Returns amount of lpShares minted for user * @param amounts - user send amounts of stablecoins to deposit * @param pid - number of the pool to which the deposit goes */
function deposit(uint256[3] memory amounts, uint256 pid) external whenNotPaused startedPool(pid) returns (uint256) { IStrategy strategy = poolInfo[pid].strategy; uint256 holdings = totalHoldings(); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { IERC20Metadata(tokens[i]).safeTransferFrom( _msgSender(), address(strategy), amounts[i] ); } } uint256 newDeposited = strategy.deposit(amounts); require(newDeposited > 0, 'Zunami: too low deposit!'); uint256 lpShares = 0; if (totalSupply() == 0) { lpShares = newDeposited; } else { lpShares = (totalSupply() * newDeposited) / holdings; } _mint(_msgSender(), lpShares); poolInfo[pid].lpShares += lpShares; totalDeposited += newDeposited; emit Deposited(_msgSender(), amounts, lpShares); return lpShares; }
0.8.12
/** * @dev withdraw in one tx, without waiting complete by dev * @param lpShares - amount of ZLP for withdraw * @param minAmounts - array of amounts stablecoins that user want minimum receive * @param pid - number of the pool from which the funds are withdrawn */
function withdraw( uint256 lpShares, uint256[3] memory minAmounts, uint256 pid ) external whenNotPaused startedPool(pid) { IStrategy strategy = poolInfo[pid].strategy; address userAddr = _msgSender(); require(balanceOf(userAddr) >= lpShares, 'Zunami: not enough LP balance'); require( strategy.withdraw(userAddr, lpShares, poolInfo[pid].lpShares, minAmounts), 'Zunami: user lps share should be at least required' ); uint256 userDeposit = (totalDeposited * lpShares) / totalSupply(); _burn(userAddr, lpShares); poolInfo[pid].lpShares -= lpShares; totalDeposited -= userDeposit; emit Withdrawn(userAddr, minAmounts, lpShares); }
0.8.12
/** @notice Check if a certain address is whitelisted to read sensitive information in the storage layer @dev if the address is an account, it is allowed to read. If the address is a contract, it has to be in the whitelist */
function senderIsAllowedToRead() internal view returns (bool _senderIsAllowedToRead) { // msg.sender is allowed to read only if its an EOA or a whitelisted contract _senderIsAllowedToRead = (msg.sender == tx.origin) || daoWhitelistingStorage().whitelist(msg.sender); }
0.4.25
/** @notice Calculate the start of a specific milestone of a specific proposal. @dev This is calculated from the voting start of the voting round preceding the milestone This would throw if the voting start is 0 (the voting round has not started yet) Note that if the milestoneIndex is exactly the same as the number of milestones, This will just return the end of the last voting round. */
function startOfMilestone(bytes32 _proposalId, uint256 _milestoneIndex) internal view returns (uint256 _milestoneStart) { uint256 _startOfPrecedingVotingRound = daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex); require(_startOfPrecedingVotingRound > 0); // the preceding voting round must have started if (_milestoneIndex == 0) { // This is the 1st milestone, which starts after voting round 0 _milestoneStart = _startOfPrecedingVotingRound .add(getUintConfig(CONFIG_VOTING_PHASE_TOTAL)); } else { // if its the n-th milestone, it starts after voting round n-th _milestoneStart = _startOfPrecedingVotingRound .add(getUintConfig(CONFIG_INTERIM_PHASE_TOTAL)); } }
0.4.25
/** @notice Calculate the actual voting start for a voting round, given the tentative start @dev The tentative start is the ideal start. For example, when a proposer finish a milestone, it should be now However, sometimes the tentative start is too close to the end of the quarter, hence, the actual voting start should be pushed to the next quarter */
function getTimelineForNextVote( uint256 _index, uint256 _tentativeVotingStart ) internal view returns (uint256 _actualVotingStart) { uint256 _timeLeftInQuarter = getTimeLeftInQuarter(_tentativeVotingStart); uint256 _votingDuration = getUintConfig(_index == 0 ? CONFIG_VOTING_PHASE_TOTAL : CONFIG_INTERIM_PHASE_TOTAL); _actualVotingStart = _tentativeVotingStart; if (timeInQuarter(_tentativeVotingStart) < getUintConfig(CONFIG_LOCKING_PHASE_DURATION)) { // if the tentative start is during a locking phase _actualVotingStart = _tentativeVotingStart.add( getUintConfig(CONFIG_LOCKING_PHASE_DURATION).sub(timeInQuarter(_tentativeVotingStart)) ); } else if (_timeLeftInQuarter < _votingDuration.add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE))) { // if the time left in quarter is not enough to vote and claim voting _actualVotingStart = _tentativeVotingStart.add( _timeLeftInQuarter.add(getUintConfig(CONFIG_LOCKING_PHASE_DURATION)).add(1) ); } }
0.4.25
/** @notice Migrate this DAO to a new DAO contract @dev This is the second step of the 2-step migration Migration can only be done during the locking phase, after the global rewards for current quarter are set. This is to make sure that there is no rewards calculation pending before the DAO is migrated to new contracts The addresses of the new Dao contracts have to be provided again, and be double checked against the addresses that were set in setNewDaoContracts() @param _newDaoContract Address of the new DAO contract @param _newDaoFundingManager Address of the new DaoFundingManager contract, which would receive the remaining ETHs in this DaoFundingManager @param _newDaoRewardsManager Address of the new daoRewardsManager contract, which would receive the claimableDGXs from this daoRewardsManager */
function migrateToNewDao( address _newDaoContract, address _newDaoFundingManager, address _newDaoRewardsManager ) public if_root() ifGlobalRewardsSet(currentQuarterNumber()) { require(isLockingPhase()); require(daoUpgradeStorage().isReplacedByNewDao() == false); require( (daoUpgradeStorage().newDaoContract() == _newDaoContract) && (daoUpgradeStorage().newDaoFundingManager() == _newDaoFundingManager) && (daoUpgradeStorage().newDaoRewardsManager() == _newDaoRewardsManager) ); daoUpgradeStorage().updateForDaoMigration(); daoFundingManager().moveFundsToNewDao(_newDaoFundingManager); daoRewardsManager().moveDGXsToNewDao(_newDaoRewardsManager); emit MigrateToNewDao(_newDaoContract, _newDaoFundingManager, _newDaoRewardsManager); }
0.4.25
/** @notice Submit a new preliminary idea / Pre-proposal @dev The proposer has to send in a collateral == getUintConfig(CONFIG_PREPROPOSAL_COLLATERAL) which he could claim back in these scenarios: - Before the proposal is finalized, by calling closeProposal() - After all milestones are done and the final voting round is passed @param _docIpfsHash Hash of the IPFS doc containing details of proposal @param _milestonesFundings Array of fundings of the proposal milestones (in wei) @param _finalReward Final reward asked by proposer at successful completion of all milestones of proposal */
function submitPreproposal( bytes32 _docIpfsHash, uint256[] _milestonesFundings, uint256 _finalReward ) external payable { senderCanDoProposerOperations(); bool _isFounder = is_founder(); require(MathHelper.sumNumbers(_milestonesFundings).add(_finalReward) <= weiInDao()); require(msg.value == getUintConfig(CONFIG_PREPROPOSAL_COLLATERAL)); require(address(daoFundingManager()).call.gas(25000).value(msg.value)()); checkNonDigixFundings(_milestonesFundings, _finalReward); daoStorage().addProposal(_docIpfsHash, msg.sender, _milestonesFundings, _finalReward, _isFounder); daoStorage().setProposalCollateralStatus(_docIpfsHash, COLLATERAL_STATUS_UNLOCKED); daoStorage().setProposalCollateralAmount(_docIpfsHash, msg.value); emit NewProposal(_docIpfsHash, msg.sender); }
0.4.25
/** @notice Modify a proposal (this can be done only before setting the final version) @param _proposalId Proposal ID (hash of IPFS doc of the first version of the proposal) @param _docIpfsHash Hash of IPFS doc of the modified version of the proposal @param _milestonesFundings Array of fundings of the modified version of the proposal (in wei) @param _finalReward Final reward on successful completion of all milestones of the modified version of proposal (in wei) */
function modifyProposal( bytes32 _proposalId, bytes32 _docIpfsHash, uint256[] _milestonesFundings, uint256 _finalReward ) external { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); require(isEditable(_proposalId)); bytes32 _currentState; (,,,_currentState,,,,,,) = daoStorage().readProposal(_proposalId); require(_currentState == PROPOSAL_STATE_PREPROPOSAL || _currentState == PROPOSAL_STATE_DRAFT); checkNonDigixFundings(_milestonesFundings, _finalReward); daoStorage().editProposal(_proposalId, _docIpfsHash, _milestonesFundings, _finalReward); emit ModifyProposal(_proposalId, _docIpfsHash); }
0.4.25
/** @notice Finalize a proposal @dev After finalizing a proposal, no more proposal version can be added. Proposer will only be able to change fundings and add more docs Right after finalizing a proposal, the draft voting round starts. The proposer would also not be able to closeProposal() anymore (hence, cannot claim back the collateral anymore, until the final voting round passes) @param _proposalId ID of the proposal */
function finalizeProposal(bytes32 _proposalId) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); require(isEditable(_proposalId)); checkNonDigixProposalLimit(_proposalId); // make sure we have reasonably enough time left in the quarter to conduct the Draft Voting. // Otherwise, the proposer must wait until the next quarter to finalize the proposal require(getTimeLeftInQuarter(now) > getUintConfig(CONFIG_DRAFT_VOTING_PHASE).add(getUintConfig(CONFIG_VOTE_CLAIMING_DEADLINE))); address _endorser; (,,_endorser,,,,,,,) = daoStorage().readProposal(_proposalId); require(_endorser != EMPTY_ADDRESS); daoStorage().finalizeProposal(_proposalId); daoStorage().setProposalDraftVotingTime(_proposalId, now); emit FinalizeProposal(_proposalId); }
0.4.25
/** @notice Function to set milestone to be completed @dev This can only be called in the Main Phase of DigixDAO by the proposer. It sets the voting time for the next milestone, which is immediately, for most of the times. If there is not enough time left in the current quarter, then the next voting is postponed to the start of next quarter @param _proposalId ID of the proposal @param _milestoneIndex Index of the milestone. Index starts from 0 (for the first milestone) */
function finishMilestone(bytes32 _proposalId, uint256 _milestoneIndex) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); uint256[] memory _currentFundings; (_currentFundings,) = daoStorage().readProposalFunding(_proposalId); // If there are N milestones, the milestone index must be < N. Otherwise, putting a milestone index of N will actually return a valid timestamp that is // right after the final voting round (voting round index N is the final voting round) // Which could be abused ( to "finish" a milestone even after the final voting round) require(_milestoneIndex < _currentFundings.length); // must be after the start of this milestone, and the milestone has not been finished yet (voting hasnt started) uint256 _startOfCurrentMilestone = startOfMilestone(_proposalId, _milestoneIndex); require(now > _startOfCurrentMilestone); require(daoStorage().readProposalVotingTime(_proposalId, _milestoneIndex.add(1)) == 0); daoStorage().setProposalVotingTime( _proposalId, _milestoneIndex.add(1), getTimelineForNextVote(_milestoneIndex.add(1), now) ); // set the voting time of next voting emit FinishMilestone(_proposalId, _milestoneIndex); }
0.4.25
/** @notice Function to update the PRL (regulatory status) status of a proposal @dev if a proposal is paused or stopped, the proposer wont be able to withdraw the funding @param _proposalId ID of the proposal @param _doc hash of IPFS uploaded document, containing details of PRL Action */
function updatePRL( bytes32 _proposalId, uint256 _action, bytes32 _doc ) public if_prl() { require(_action == PRL_ACTION_STOP || _action == PRL_ACTION_PAUSE || _action == PRL_ACTION_UNPAUSE); daoStorage().updateProposalPRL(_proposalId, _action, _doc, now); emit PRLAction(_proposalId, _action, _doc); }
0.4.25
/** @notice Function to close proposal (also get back collateral) @dev Can only be closed if the proposal has not been finalized yet @param _proposalId ID of the proposal */
function closeProposal(bytes32 _proposalId) public { senderCanDoProposerOperations(); require(isFromProposer(_proposalId)); bytes32 _finalVersion; bytes32 _status; (,,,_status,,,,_finalVersion,,) = daoStorage().readProposal(_proposalId); require(_finalVersion == EMPTY_BYTES); require(_status != PROPOSAL_STATE_CLOSED); require(daoStorage().readProposalCollateralStatus(_proposalId) == COLLATERAL_STATUS_UNLOCKED); daoStorage().closeProposal(_proposalId); daoStorage().setProposalCollateralStatus(_proposalId, COLLATERAL_STATUS_CLAIMED); emit CloseProposal(_proposalId); require(daoFundingManager().refundCollateral(msg.sender, _proposalId)); }
0.4.25
/** @notice Function for founders to close all the dead proposals @dev Dead proposals = all proposals who are not yet finalized, and been there for more than the threshold time The proposers of dead proposals will not get the collateral back @param _proposalIds Array of proposal IDs */
function founderCloseProposals(bytes32[] _proposalIds) external if_founder() { uint256 _length = _proposalIds.length; uint256 _timeCreated; bytes32 _finalVersion; bytes32 _currentState; for (uint256 _i = 0; _i < _length; _i++) { (,,,_currentState,_timeCreated,,,_finalVersion,,) = daoStorage().readProposal(_proposalIds[_i]); require(_finalVersion == EMPTY_BYTES); require( (_currentState == PROPOSAL_STATE_PREPROPOSAL) || (_currentState == PROPOSAL_STATE_DRAFT) ); require(now > _timeCreated.add(getUintConfig(CONFIG_PROPOSAL_DEAD_DURATION))); emit CloseProposal(_proposalIds[_i]); daoStorage().closeProposal(_proposalIds[_i]); } }
0.4.25
/** * @dev Execute multiple trades in a single transaction. * @param wrappers Addresses of exchange wrappers. * @param token Address of ERC20 token to receive in first trade. * @param trade1 Calldata of Ether => ERC20 trade. * @param trade2 Calldata of ERC20 => Ether trade. */
function trade( address[2] wrappers, address token, bytes trade1, bytes trade2 ) external payable { // Execute the first trade to get tokens require(execute(wrappers[0], msg.value, trade1)); uint256 tokenBalance = IERC20(token).balanceOf(this); // Transfer tokens to the next exchange wrapper transfer(token, wrappers[1], tokenBalance); // Execute the second trade to get Ether require(execute(wrappers[1], 0, trade2)); // Send the arbitrageur Ether msg.sender.transfer(address(this).balance); }
0.4.24
/** * @dev Transfer function to assign a token to another address * Reverts if the address already owns a token * @param from address the address that currently owns the token * @param to address the address to assign the token to * @param tokenId uint256 ID of the token to transfer */
function transferFrom( address from, address to, uint256 tokenId ) public isValidAddress(to) isValidAddress(from) onlyOwner { require(tokenOwned[to] == 0, "Destination address already owns a token"); require(ownerOf[tokenId] == from, "From address does not own token"); tokenOwned[from] = 0; tokenOwned[to] = tokenId; ownerOf[tokenId] = to; emit Transfer(from, to, tokenId); }
0.5.17
/** * @dev Burn function to remove a given tokenId * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to burn */
function burn(uint256 tokenId) public onlyOwner { address previousOwner = ownerOf[tokenId]; require(previousOwner != address(0), "ERC721: token does not exist"); delete tokenOwned[previousOwner]; delete ownerOf[tokenId]; for (uint256 i = 0; i < tokens.length; i++) { if (tokens[i] == tokenId) { tokens[i] = tokens[tokens.length - 1]; break; } } tokens.pop(); if (bytes(tokenURIs[tokenId]).length != 0) { delete tokenURIs[tokenId]; } emit Burn(tokenId); }
0.5.17
/// @notice The actual mint function used for presale and public minting then. /// @param amount The number of tokens you're able to mint in one transaction.
function mint(uint256 amount) external payable { require(!saleIsClosed, "The sale is closed."); require(amount > 0 && amount <= 3, "Amount must be within [1;3]."); if(whitelistSaleIsActive){ // check if we are in presale require(hasRole(WHITELIST_ROLE, msg.sender), "You're not on the whitelist."); require(whitelistPasses[msg.sender] != 0 && (whitelistPasses[msg.sender] - amount) >= 0, "You are out of utility."); require(whitelistCurrentLimit > 0, "We're out of tokens."); }else{ // if not check if the public sale is active and we're in the limits require(saleIsActive, "Sale not active yet."); require(publicCurrentLimit > 0, "We're out of tokens."); } require((_tokenIdCounter.current() + amount) <= MAX_SUPPLY , "Out of tokens."); require(msg.value == (41000000000000000 * amount), "The amount of ether is wrong."); for(uint256 idx = 1; idx <= amount; idx++){ if(hasRole(WHITELIST_ROLE, msg.sender)){ // make sure we reduce the amount of whitelistPasses left of the user and reduce the total limit whitelistPasses[msg.sender]--; whitelistCurrentLimit--; }else{ publicCurrentLimit--; } _tokenIdCounter.increment(); _safeMint(msg.sender, _tokenIdCounter.current()); utilityState[_tokenIdCounter.current()] = 3; } }
0.8.4
/// @notice Admin mint function that is used for preminting NFTs. /// @param amount The amount of NFTs that can be minted in one transaction.
function adminMint(address receiver, uint256 amount) external onlyOwner{ require(!saleIsClosed, "The sale is closed."); require(_tokenIdReserveCounter.current() < MAX_RESERVE , "Out of reserve tokens."); require(amount > 0 && amount <= 20, "Amount must be within [1;20]."); for(uint256 idx = 1; idx <= amount; idx++){ _tokenIdReserveCounter.increment(); _tokenIdCounter.increment(); _safeMint(receiver, _tokenIdCounter.current()); utilityState[_tokenIdCounter.current()] = 3; } }
0.8.4
/// @dev claim tokenId mints with placeholder URI in batch 'phase'
function safeMint() external payable nonReentrant { // check mint is open require(mintOpen, 'CLOSED'); // check whitelist, if flipped on if (whitelistOn) require(whitelist[msg.sender], 'NOT_WHITELISTED'); // check if price attached require(msg.value == mintPrice, 'BAD_PRICE'); // increment Id for mint (we want to match supply for ease) _tokenIdCounter.increment(); // set tokenId uint256 tokenId = _tokenIdCounter.current(); // check new Id doesn't pass mint limit for phase require(tokenId <= mintPhaseLimit, 'PHASE_LIMIT'); // mint Id to caller _safeMint(msg.sender, tokenId); // set Id placeholder URI _setTokenURI(tokenId, placeholderURI); // forward ETH to contract owner _safeTransferETH(owner(), msg.value); }
0.8.10
/// **** MINT MGMT /// @dev set next phase for minting (limit + price)
function setMintPhase(uint256 mintPhaseLimit_, uint256 mintPrice_) external onlyOwner { // ensure Id limit doesn't exceed cap require(mintPhaseLimit_ <= mintCap, 'CAPPED'); // ensure Id limit is greater than current supply (increasing phase) require(mintPhaseLimit_ > totalSupply(), 'BAD_LIMIT'); // set new minting limit under cap mintPhaseLimit = mintPhaseLimit_; // set new minting price mintPrice = mintPrice_; // increment phase for tracking mintPhase++; }
0.8.10
/// @dev update minted URIs
function setURIs(uint256[] calldata tokenIds, string[] calldata uris) external onlyOwner { require(tokenIds.length == uris.length, 'NO_ARRAY_PARITY'); // this is reasonably safe from overflow because incrementing `i` loop beyond // 'type(uint256).max' is exceedingly unlikely compared to optimization benefits unchecked { for (uint256 i; i < tokenIds.length; i++) { _setTokenURI(tokenIds[i], uris[i]); } } }
0.8.10
/// @dev ETH tranfer helper - optimized in assembly:
function _safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // transfer the ETH and store if it succeeded or not callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, 'ETH_TRANSFER_FAILED'); }
0.8.10
/** * @dev Reserved for giveaways. */
function reserveGiveaway(uint256 numTokens) public onlyOwner { uint currentSupply = totalSupply(); require(totalSupply() + numTokens <= 10, "10 mints for sale giveaways"); uint256 index; // Reserved for people who helped this project and giveaways for (index = 0; index < numTokens; index++) { _safeMint(owner(), currentSupply + index); } }
0.7.6
/* * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
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"); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); }
0.8.0
// Purchase tokens
function buyTokens(address beneficiary) public nonReentrant payable whenNotPaused { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; uint256 returnWeiAmount; // calculate token amount to be created uint rate = getRate(); assert(rate > 0); uint256 tokens = weiAmount.mul(rate); uint256 newsoldTokens = soldTokens.add(tokens); if (newsoldTokens > contractCap) { newsoldTokens = contractCap; tokens = contractCap.sub(soldTokens); uint256 newWeiAmount = tokens.div(rate); returnWeiAmount = weiAmount.sub(newWeiAmount); weiAmount = newWeiAmount; } // update state weiRaised = weiRaised.add(weiAmount); token.transfer(beneficiary, tokens); soldTokens = newsoldTokens; if (returnWeiAmount > 0){ msg.sender.transfer(returnWeiAmount); } emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); }
0.5.11
/** * @dev Bootstrap the supply distribution and fund the UniswapV2 liquidity pool */
function bootstrap() external returns (bool){ require(isBootStrapped == false, 'Require unintialized token'); require(msg.sender == owner, 'Require ownership'); //Distribute tokens uint256 premineAmount = 100000000 * (10 ** 18); //100 mil uint256 marketingAmount = 1000000000 * (10 ** 18); // 1 bil for justin sun balances[marketingAccount] = marketingAmount; emit Transfer(address(0), marketingAccount, marketingAmount); for (uint256 i = 0; i < 15; i++) { balances[ambassadorList[i]] = premineAmount; emit Transfer(address(0), ambassadorList[i], balances[ambassadorList[i]]); } balances[owner] = _totalSupply.sub(marketingAmount + 15 * premineAmount); emit Transfer(address(0), owner, balances[owner]); isBootStrapped = true; return isBootStrapped; }
0.6.2
// the function is name differently to not cause inheritance clash in truffle and allows tests
function initializeVault(address _storage, address _underlying, uint256 _toInvestNumerator, uint256 _toInvestDenominator ) public initializer { require(_toInvestNumerator <= _toInvestDenominator, "cannot invest more than 100%"); require(_toInvestDenominator != 0, "cannot divide by 0"); ERC20Detailed.initialize( string(abi.encodePacked("DELTA_", ERC20Detailed(_underlying).symbol())), string(abi.encodePacked("d", ERC20Detailed(_underlying).symbol())), ERC20Detailed(_underlying).decimals() ); ControllableInit.initialize( _storage ); uint256 underlyingUnit = 10 ** uint256(ERC20Detailed(address(_underlying)).decimals()); uint256 implementationDelay = 12 hours; uint256 strategyChangeDelay = 12 hours; VaultStorage.initialize( _underlying, _toInvestNumerator, _toInvestDenominator, underlyingUnit, implementationDelay, strategyChangeDelay ); }
0.5.16
//Get the tokens that exist for this wallet
function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; }
0.8.0
// if any applicable tokens are held by this contract, it should be able to deposit them
function _depositAssets () internal { uint LPBalance = IERC20(liquidity).balanceOf(address(this)); // load LP balance into memory if(LPBalance > 0) // are there any LP tokens? IStakingRewards(staking).deposit(LPBalance); // deposit the entire amount into the StakingRewards contract uint krillBalance = IERC20(krill).balanceOf(address(this)); // load KRILL balance into memory if(krillBalance > 0 ) // is there any krill here dumped from another contract? ICompounder(cKrill).buy(krillBalance); // buy cKRILL with whatever balance is held }
0.8.7
// claim rewards from NFTs, staking, and cKRILL position
function _claimRewardsAndDisburse() internal { IClaimable(staking).claim(); // Claim rewards from the LP staking contract IClaimable(whalesGame).claim(); // Claim rewards from the whales game contract if(ICompounder(cKrill).dividendsOf(address(this)) > 0) // If this contract has rewards to claim ICompounder(cKrill).withdraw(); // Claim rewards from the cKRILL held by this contract uint krillBalance = IERC20(krill).balanceOf(address(this)); // load KRILL balance into memory if(krillBalance > 0) // is there any krill here dumped from another contract? IERC20(krill).burn(krillBalance); // burn it all }
0.8.7
// Callback function, distribute tokens to sender when ETH donation is recieved
function () payable public { require(isLive); uint256 donation = msg.value; uint256 amountZNT = donation * rateOfZNT; uint256 amountZLT = donation * rateOfZLT; require(availableZNT >= amountZNT && availableZLT >= amountZLT); donationOf[msg.sender] += donation; amountEthRaised += donation; availableZNT -= amountZNT; availableZLT -= amountZLT; tokenZNT.transfer(msg.sender, amountZNT); tokenZLT.transfer(msg.sender, amountZLT); beneficiary.transfer(donation); }
0.4.24
/** * @dev Resets the player's current progress. */
function resetProgress() public returns (bool) { if (playerCurrentProgress[msg.sender] > 0) { playerCurrentProgress[msg.sender] = 0; playerAddressToBid[msg.sender] = 0; playerAddressToRollUnder[msg.sender] = 0; emit ResetProgress( msg.sender, true ); return true; } else { return false; } }
0.4.24
/** * @dev Calculates the payout based on roll under in Wei. */
function _calculatePayout( uint256 rollUnder, uint256 value) internal view isWithinLimits(value) returns (uint256) { require(rollUnder >= minRoll && rollUnder <= maxRoll, "invalid roll under number!"); uint256 _totalPayout = 0 wei; _totalPayout = ((((value * (100-(SafeMath.sub(rollUnder,1)))) / (SafeMath.sub(rollUnder,1))+value))*platformCutPayout/platformCutPayoutDivisor)-value; return _totalPayout; }
0.4.24
/* at initialization, setup the owner */
function WowanderICOPrivateCrowdSale( address addressOfTokenUsedAsReward, address addressOfBeneficiary ) public { beneficiary = addressOfBeneficiary; //startTime = 1516021200; startTime = 1516021200 - 3600 * 24; // TODO remove duration = 744 hours; tokensContractBalance = 5 * 0.1 finney; price = 0.000000000005 * 1 ether; discountPrice = 0.000000000005 * 1 ether * 0.9; tokenReward = WWWToken(addressOfTokenUsedAsReward); }
0.4.18
/** * @dev Transfer several token for a specified addresses * @param _to The array of addresses to transfer to. * @param _value The array of amounts to be transferred. */
function massTransfer(address[] memory _to, uint[] memory _value) public returns (bool){ require(_to.length == _value.length, "You have different amount of addresses and amounts"); uint len = _to.length; for(uint i = 0; i < len; i++){ if(!_transfer(_to[i], _value[i])){ return false; } } return true; }
0.5.12
/** * @dev Emit new tokens and transfer from 0 to client address. This function will generate 21.5% of tokens for management address as well. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function _mint(address _to, uint _value) private returns (bool){ require(_to != address(0), "Receiver address cannot be null"); require(_to != address(this), "Receiver address cannot be ITCM contract address"); require(_value > 0 && _value <= leftToMint, "Looks like we are unable to mint such amount"); // 21.5% of token amount to management address uint managementAmount = _value.mul(215).div(1000); leftToMint = leftToMint.sub(_value); totalSupply = totalSupply.add(_value); totalSupply = totalSupply.add(managementAmount); balances[_to] = balances[_to].add(_value); balances[managementProfitAddr] = balances[managementProfitAddr].add(managementAmount); emit Transfer(address(0), _to, _value); emit Transfer(address(0), managementProfitAddr, managementAmount); return true; }
0.5.12
/** * @dev This is wrapper for _mint. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function mint(address _to, uint _value) public returns (bool){ require(msg.sender != address(0), "Sender address cannon be null"); require(msg.sender == mintingAllowedForAddr || mintingAllowedForAddr == address(0) && msg.sender == contractCreator, "You are unavailable to mint tokens"); return _mint(_to, _value); }
0.5.12
/** * @dev Similar to mint function but take array of addresses and values. * @param _to The addresses to transfer to. * @param _value The amounts to be transferred. */
function mint(address[] memory _to, uint[] memory _value) public returns (bool){ require(_to.length == _value.length, "You have different amount of addresses and amounts"); require(msg.sender != address(0), "Sender address cannon be null"); require(msg.sender == mintingAllowedForAddr || mintingAllowedForAddr == address(0) && msg.sender == contractCreator, "You are unavailable to mint tokens"); uint len = _to.length; for(uint i = 0; i < len; i++){ if(!_mint(_to[i], _value[i])){ return false; } } return true; }
0.5.12
/** * @dev Set a contract address that allowed to mint tokens. * @param _address The address of another contract. */
function setMintingContractAddress(address _address) public returns (bool){ require(mintingAllowedForAddr == address(0) && msg.sender == contractCreator, "Only contract creator can set minting contract and only when it is not set"); mintingAllowedForAddr = _address; return true; }
0.5.12
// Guards against integer overflows
function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } else { uint256 c = a * b; assert(c / a == b); return c; } }
0.5.17
/** * @dev this function will send the Team tokens to given address * @param _teamAddress ,address of the bounty receiver. * @param _value , number of tokens to be sent. */
function sendTeamTokens(address _teamAddress, uint256 _value) external whenNotPaused onlyOwner returns (bool) { require(teamTokens >= _value); totalReleased = totalReleased.add(_value); require(totalReleased <= totalSupply()); teamTokens = teamTokens.sub(_value); teamTokenHolder[_teamAddress] = true; teamTokenInitially[_teamAddress] = teamTokenInitially[_teamAddress].add((_value.mul(95)).div(100)); teamLockPeriodStart[_teamAddress] = now; super._transfer(address(this),_teamAddress,(_value.mul(5)).div(100)); return true; }
0.5.0
/** * @notice Mints the vault shares to the msg.sender * @param amount is the amount of `asset` deposited */
function _deposit(uint256 amount) private { uint256 totalWithDepositedAmount = totalBalance(); // amount needs to be subtracted from totalBalance because it has already been // added to it from either IWETH.deposit and IERC20.safeTransferFrom uint256 total = totalWithDepositedAmount.sub(amount); uint256 shareSupply = totalSupply(); // Following the pool share calculation from Alpha Homora: // solhint-disable-next-line // https://github.com/AlphaFinanceLab/alphahomora/blob/340653c8ac1e9b4f23d5b81e61307bf7d02a26e8/contracts/5/Bank.sol#L104 uint256 share = shareSupply == 0 ? amount : amount.mul(shareSupply).div(total); _mint(msg.sender, share); }
0.8.3
/** * @dev Get withdraw amount of shares value * @param shares How many shares will be exchanged */
function getWithdrawAmount(uint256 shares, address _addr) public view returns (uint256 amount) { uint256 PPS; //check if last user: cannot use shares, could be partial withdraw uint256 userShareBalance = balanceOf(_addr); if (userShareBalance == totalSupply()) { //last user PPS = getPricePerShare(currentRound); } else { PPS = getPricePerShare(currentRound.sub(1)); } amount = (shares.mul(PPS)).div(ppsMultiplier); }
0.8.3
/** * @dev Get mint amount for roll() * @param timestamp current timestamp */
function getMintAmount(uint timestamp) public view returns (uint256 amount) { if (timestamp < deployTime + 31557600) { amount = am1 ; } else { if (timestamp < deployTime + 63115200) { amount = am2 ; } else { if (timestamp < deployTime + 94672800) { amount = am3 ; } else { amount = am4 ; } } } }
0.8.3
/* * @notice Rolls the vault's funds into a new short position. */
function roll() external onlyOwner { require(block.timestamp >= readyAt, "not ready to roll yet"); uint mintAmount = getMintAmount(block.timestamp)/52 ; token_contract.extMint(address(this), mintAmount); readyAt = block.timestamp.add(WEEK); currentRound = currentRound.add(1); roundPricePerShare[currentRound] = getPricePerShare(currentRound); emit Roll(currentRound, roundPricePerShare[currentRound]); }
0.8.3
/** * @dev Get pricePerShare of a certain round (multiplied with ppsMultiplier!) * @param round Round to get the pricePerShare */
function getPricePerShare(uint256 round) public view returns (uint256 pps) { if (round == currentRound) { uint256 _assetBalance = assetBalance(); uint256 _shareSupply = totalSupply(); if (_shareSupply == 0) { pps = 1; } else { pps = (_assetBalance.mul(ppsMultiplier)).div(_shareSupply); } } else { pps = roundPricePerShare[round]; } }
0.8.3
// ------------------------------------------------------------------------ // 5 vev Tokens per 0.1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 10; } else { tokens = msg.value * 5; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); _totalSupply = safeAdd(_totalSupply, tokens); Transfer(address(0), msg.sender, tokens); owner.transfer(msg.value); }
0.4.25
/** * @notice Using a minimal proxy contract pattern initialises the contract and sets delegation * @dev initialises the VestingDepositAccount (see https://eips.ethereum.org/EIPS/eip-1167) * @dev only controller */
function init(address _tokenAddress, address _controller, address _beneficiary) external { require(controller == address(0), "VestingDepositAccount::init: Contract already initialized"); token = FuelToken(_tokenAddress); controller = _controller; beneficiary = _beneficiary; // sets the beneficiary as the delegate on the token token.delegate(beneficiary); }
0.5.16
/** * @notice Create a new vesting schedule * @notice A transfer is used to bring tokens into the VestingDepositAccount so pre-approval is required * @notice Delegation is set for the beneficiary on the token during schedule creation * @param _beneficiary beneficiary of the vested tokens * @param _amount amount of tokens (in wei) */
function createVestingSchedule(address _beneficiary, uint256 _amount) external returns (bool) { require(msg.sender == owner, "VestingContract::createVestingSchedule: Only Owner"); require(_beneficiary != address(0), "VestingContract::createVestingSchedule: Beneficiary cannot be empty"); require(_amount > 0, "VestingContract::createVestingSchedule: Amount cannot be empty"); // Ensure only one per address require( vestingSchedule[_beneficiary].amount == 0, "VestingContract::createVestingSchedule: Schedule already in flight" ); // Set up the vesting deposit account for the _beneficiary address depositAccountAddress = createClone(baseVestingDepositAccount); VestingDepositAccount depositAccount = VestingDepositAccount(depositAccountAddress); depositAccount.init(address(token), address(this), _beneficiary); // Create schedule vestingSchedule[_beneficiary] = Schedule({ amount : _amount, depositAccount : depositAccount }); // Vest the tokens into the deposit account and delegate to the beneficiary require( token.transferFrom(msg.sender, address(depositAccount), _amount), "VestingContract::createVestingSchedule: Unable to transfer tokens to VDA" ); emit ScheduleCreated(_beneficiary, _amount); return true; }
0.5.16
/** * @notice Updates a schedule beneficiary * @notice Voids the old schedule and transfers remaining amount to new beneficiary via a new schedule * @dev Only owner * @param _currentBeneficiary beneficiary to be replaced * @param _newBeneficiary beneficiary to vest remaining tokens to */
function updateScheduleBeneficiary(address _currentBeneficiary, address _newBeneficiary) external { require(msg.sender == owner, "VestingContract::updateScheduleBeneficiary: Only owner"); // retrieve existing schedule Schedule memory schedule = vestingSchedule[_currentBeneficiary]; require( schedule.amount > 0, "VestingContract::updateScheduleBeneficiary: There is no schedule currently in flight" ); require(_drawDown(_currentBeneficiary), "VestingContract::_updateScheduleBeneficiary: Unable to drawn down"); // the old schedule is now void voided[_currentBeneficiary] = true; // setup new schedule with the amount left after the previous beneficiary's draw down vestingSchedule[_newBeneficiary] = Schedule({ amount : schedule.amount.sub(totalDrawn[_currentBeneficiary]), depositAccount : schedule.depositAccount }); vestingSchedule[_newBeneficiary].depositAccount.switchBeneficiary(_newBeneficiary); }
0.5.16
/** * @notice Vesting schedule and associated data for a beneficiary * @dev Must be called directly by the beneficiary assigned the tokens in the schedule * @return _amount * @return _totalDrawn * @return _lastDrawnAt * @return _drawDownRate * @return _remainingBalance * @return _depositAccountAddress */
function vestingScheduleForBeneficiary(address _beneficiary) external view returns ( uint256 _amount, uint256 _totalDrawn, uint256 _lastDrawnAt, uint256 _drawDownRate, uint256 _remainingBalance, address _depositAccountAddress ) { Schedule memory schedule = vestingSchedule[_beneficiary]; return ( schedule.amount, totalDrawn[_beneficiary], lastDrawnAt[_beneficiary], schedule.amount.div(end.sub(start)), schedule.amount.sub(totalDrawn[_beneficiary]), address(schedule.depositAccount) ); }
0.5.16
/** * @dev External function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */
function mint(address to, uint256 tokenId, uint256 metadataHash) external payable { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); require(msg.value >= _mintFee, "Fee not provided"); _feeRecipient.transfer(msg.value); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); _tokenMetadataHashes[tokenId] = metadataHash; _addTokenToOwnerEnumeration(to, tokenId); _addTokenToAllTokensEnumeration(tokenId); }
0.5.17
/** Claims tokens for free paying only gas fees */
function preMint( uint256 number, bytes32 messageHash, bytes calldata signature ) external virtual { require( hashMessage(number, msg.sender) == messageHash, "MESSAGE_INVALID" ); require( verifyAddressSigner(giftAddress, messageHash, signature), "SIGNATURE_VALIDATION_FAILED" ); require( premintClaimed[msg.sender] == false, "CryptoWolvesClub: You already claimed your premint tokens." ); premintClaimed[msg.sender] = true; for (uint256 i = 0; i < number; i++) { _safeMint(msg.sender, _tokenIdCounter.current()); _tokenIdCounter.increment(); } }
0.8.7
/** * @dev Set a token with a specific crew collection * @param _crewId The ERC721 tokenID for the crew member * @param _collId The set ID to assign the crew member to * @param _mod An optional modifier ranging from 0 (default) to 10,000 */
function setToken(uint _crewId, uint _collId, uint _mod) external onlyManagers { require(address(_generators[_collId]) != address(0), "CrewFeatures: collection must be defined"); _crewCollection[_crewId] = _collId; if (_mod > 0) { _crewModifiers[_crewId] = _mod; } }
0.7.6
// ============ Only-Solo Functions ============
function getTradeCost( uint256 inputMarketId, uint256 outputMarketId, Account.Info memory /* makerAccount */, Account.Info memory takerAccount, Types.Par memory oldInputPar, Types.Par memory newInputPar, Types.Wei memory inputWei, bytes memory /* data */ ) public /* view */ returns (Types.AssetAmount memory) { Require.that( g_migrators[takerAccount.owner], FILE, "Migrator not approved", takerAccount.owner ); Require.that( inputMarketId == SAI_MARKET && outputMarketId == DAI_MARKET, FILE, "Invalid markets" ); // require that SAI amount is getting smaller (closer to zero) if (oldInputPar.isPositive()) { Require.that( inputWei.isNegative(), FILE, "inputWei must be negative" ); Require.that( !newInputPar.isNegative(), FILE, "newInputPar cannot be negative" ); } else if (oldInputPar.isNegative()) { Require.that( inputWei.isPositive(), FILE, "inputWei must be positive" ); Require.that( !newInputPar.isPositive(), FILE, "newInputPar cannot be positive" ); } else { Require.that( inputWei.isZero() && newInputPar.isZero(), FILE, "inputWei must be zero" ); } /* return the exact opposite amount of SAI in DAI */ return Types.AssetAmount ({ sign: !inputWei.sign, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: inputWei.value }); }
0.5.7
// concatenate the baseURI with the tokenId
function tokenURI(uint256 tokenId) public view virtual override returns(string memory) { require(_exists(tokenId), "token does not exist"); if (tokenIdToFrozenForArt[tokenId]) { string memory lockedBaseURI = _lockedBaseURI(); return bytes(lockedBaseURI).length > 0 ? string(abi.encodePacked(lockedBaseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : ""; } string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, Strings.toString(tokenIdToMetadataId[tokenId]))) : ""; }
0.8.7
// Used to request a 3D body for your voxmon // Freezes transfers re-rolling a voxmon
function request3DArt(uint256 tokenId) external { require(block.timestamp >= artStartTime, "you cannot freeze your Voxmon yet"); require(ownerOf(tokenId) == msg.sender, "you must own this token to request Art"); require(tokenIdToFrozenForArt[tokenId] == false, "art has already been requested for that Voxmon"); tokenIdToFrozenForArt[tokenId] = true; emit artRequestedEvent(msg.sender, tokenId); }
0.8.7
// Mint a Voxmon // Cost is 0.07 ether
function mint(address recipient) payable public returns (uint256) { require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one"); require(msg.value >= MINT_COST, "not enough ether, minting costs 0.07 ether"); require(block.timestamp >= startingTime, "public mint hasn\'t started yet"); _tokensMinted.increment(); uint256 newTokenId = _tokensMinted.current(); uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current(); _mint(recipient, newTokenId); tokenIdToMetadataId[newTokenId] = metadataId; emit mintEvent(recipient, newTokenId, metadataId); return newTokenId; }
0.8.7
// Mint multiple Voxmon // Cost is 0.07 ether per Voxmon
function mint(address recipient, uint256 numberToMint) payable public returns (uint256[] memory) { require(numberToMint > 0); require(numberToMint <= 10, "max 10 voxmons per transaction"); require(msg.value >= MINT_COST * numberToMint); uint256[] memory tokenIdsMinted = new uint256[](numberToMint); for(uint i = 0; i < numberToMint; i++) { tokenIdsMinted[i] = mint(recipient); } return tokenIdsMinted; }
0.8.7
// Mint a free Voxmon
function preReleaseMint(address recipient) public returns (uint256) { require(remainingPreReleaseMints[msg.sender] > 0, "you have 0 remaining pre-release mints"); remainingPreReleaseMints[msg.sender] = remainingPreReleaseMints[msg.sender] - 1; require(_isTokenAvailable(), "max live supply reached, to get a new Voxmon you\'ll need to reroll an old one"); _tokensMinted.increment(); uint256 newTokenId = _tokensMinted.current(); uint256 metadataId = _tokensMinted.current() + _tokensRerolled.current(); _mint(recipient, newTokenId); tokenIdToMetadataId[newTokenId] = metadataId; emit mintEvent(recipient, newTokenId, metadataId); return newTokenId; }
0.8.7
// Mint multiple free Voxmon
function preReleaseMint(address recipient, uint256 numberToMint) public returns (uint256[] memory) { require(remainingPreReleaseMints[msg.sender] >= numberToMint, "You don\'t have enough remaining pre-release mints"); uint256[] memory tokenIdsMinted = new uint256[](numberToMint); for(uint i = 0; i < numberToMint; i++) { tokenIdsMinted[i] = preReleaseMint(recipient); } return tokenIdsMinted; }
0.8.7
// Re-Roll a Voxmon // Cost is 0.01 ether
function reroll(uint256 tokenId) payable public returns (uint256) { require(ownerOf(tokenId) == msg.sender, "you must own this token to reroll"); require(msg.value >= REROLL_COST, "not enough ether, rerolling costs 0.03 ether"); require(tokenIdToFrozenForArt[tokenId] == false, "this token is frozen"); _tokensRerolled.increment(); uint256 newMetadataId = _tokensMinted.current() + _tokensRerolled.current(); tokenIdToMetadataId[tokenId] = newMetadataId; emit rerollEvent(msg.sender, tokenId, newMetadataId); return newMetadataId; }
0.8.7
/** * @dev For each boosted vault, poke all the over boosted accounts. * @param _vaultAccounts An array of PokeVaultAccounts structs */
function poke(PokeVaultAccounts[] memory _vaultAccounts) external { uint vaultCount = _vaultAccounts.length; for(uint i = 0; i < vaultCount; i++) { PokeVaultAccounts memory vaultAccounts = _vaultAccounts[i]; address boostVaultAddress = vaultAccounts.boostVault; require(boostVaultAddress != address(0), "blank vault address"); IBoostedVaultWithLockup boostVault = IBoostedVaultWithLockup(boostVaultAddress); uint accountsLength = vaultAccounts.accounts.length; for(uint j = 0; j < accountsLength; j++) { address accountAddress = vaultAccounts.accounts[j]; require(accountAddress != address(0), "blank address"); boostVault.pokeBoost(accountAddress); } } }
0.8.2
// public sale
function safeMint(uint8 count) external payable { require(saleState == 3, "public sale is not begun"); require(count > 0 && count <= 3, "invalid count"); uint256 price = tokenPrice * count; require(msg.value >= price, "insufficient value"); payable(owner()).transfer(price); payable(_msgSender()).transfer(msg.value - price); require(balanceOf(_msgSender()) < 9, "public sale max total buy reached"); for (uint256 i = 0; i < count; i++) { _safeMint(_msgSender(), _tokenId++); } }
0.8.12
// burn tokens, allowing sent ETH to be converted according to gweiPerGoof
function burnTokens(uint256 amount) private { if (msg.value > 0 && gweiPerGoof > 0) { uint256 converted = (msg.value * 1 gwei) / gweiPerGoof; if (converted >= amount) { amount = 0; } else { amount -= converted; } } if (amount > 0) { _burn(msg.sender, amount); } }
0.8.9
// This is the function that will be called postLoan // i.e. Encode the logic to handle your flashloaned funds here
function callFunction( address sender, Account.Info memory account, bytes memory data ) public { MyCustomData memory mcd = abi.decode(data, (MyCustomData)); IERC20 token1 = IERC20(mcd.loanedToken); IERC20 token2 = IERC20(mcd.otherToken); // STEP 1 - TRADE LOANED TOKEN TO OTHER TOKEN //////////////////////////////// token1.approve(OneSplitAddress,0); token1.approve(OneSplitAddress,mcd.repayAmount-2); (uint256 returnAmount1, uint256[] memory distribution1) = IOneSplit( OneSplitAddress ).getExpectedReturn( token1, token2, mcd.repayAmount-2, 10, 0 ); uint256 balanceBefore1 = token2.balanceOf(address(this)); IOneSplit(OneSplitAddress).swap( token1, token2, mcd.repayAmount-2, returnAmount1, distribution1, 0 ); uint256 balanceAfter1 = token2.balanceOf(address(this)); uint256 result1 = balanceAfter1 - balanceBefore1; // STEP 2 - TRADE OTHER TOKEN BACK TO LOANED TOKEN /////////////////////////// token2.approve(OneSplitAddress,0); token2.approve(OneSplitAddress,result1); (uint256 returnAmount2, uint256[] memory distribution2) = IOneSplit( OneSplitAddress ).getExpectedReturn( token2, token1, result1, 10, 0 ); uint256 balanceBefore2 = token1.balanceOf(address(this)); IOneSplit(OneSplitAddress).swap( token2, token1, result1, returnAmount2, distribution2, 0 ); uint256 balanceAfter2 = token1.balanceOf(address(this)); uint256 result2 = balanceAfter2 - balanceBefore2; // STEP 3 - CALCULATE PROFIT ///////////////////////////////////////////////// require(mcd.repayAmount < (result2-mcd.gasFee), "No profit."); }
0.5.0
/** * @dev transfer token for a specified address and forward the parameters to token recipient if any * @param _to The address to transfer to. * @param _value The amount to be transferred. * @param _param1 Parameter 1 for the token recipient * @param _param2 Parameter 2 for the token recipient * @param _param3 Parameter 3 for the token recipient */
function transferWithParams(address _to, uint256 _value, uint256 _param1, uint256 _param2, uint256 _param3) onlyPayloadSize(5 * 32) external returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); _invokeTokenRecipient(msg.sender, _to, _value, _param1, _param2, _param3); return true; }
0.4.21
/** * @dev Buyouts a position's collateral * @param asset The address of the main collateral token of a position * @param user The owner of a position **/
function buyout(address asset, address user) public nonReentrant { require(vault.liquidationBlock(asset, user) != 0, "Unit Protocol: LIQUIDATION_NOT_TRIGGERED"); uint startingPrice = vault.liquidationPrice(asset, user); uint blocksPast = block.number.sub(vault.liquidationBlock(asset, user)); uint devaluationPeriod = vaultManagerParameters.devaluationPeriod(asset); uint debt = vault.getTotalDebt(asset, user); uint penalty = debt.mul(vault.liquidationFee(asset, user)).div(DENOMINATOR_1E2); uint mainAssetInPosition = vault.collaterals(asset, user); uint colInPosition = vault.colToken(asset, user); uint mainToLiquidator; uint colToLiquidator; uint mainToOwner; uint colToOwner; uint repayment; (mainToLiquidator, colToLiquidator, mainToOwner, colToOwner, repayment) = _calcLiquidationParams( devaluationPeriod, blocksPast, startingPrice, debt.add(penalty), mainAssetInPosition, colInPosition ); _liquidate( asset, user, mainToLiquidator, colToLiquidator, mainToOwner, colToOwner, repayment, penalty ); }
0.7.5
/** * @notice The aim is to create a conditional payment and find someone to buy the counter position * * Parameters to forward to master contract: * @param long .. Decide if you want to be in the long or short position of your contract. * @param dueDate .. Set a due date of your contract. Make sure this is supported by us. Use OD.exchange to avoid conflicts here. * @param strikePrice .. Choose a strike price which will be used at due date for calculation of your payout. Make sure that the format is correct. Use OD.exchange to avoid mistakes. */
function createContractWithBounty ( bool long, uint256 dueDate, uint256 strikePrice ) payable public { // New conditional payment must be created before deadline exceeded require(now < deadline); // Only once per creator address require(!bountyPermission[msg.sender]); bountyPermission[msg.sender] = true; // Only first customers can get bounty numberOfGivenBounties += 1; require(numberOfGivenBounties <= maxNumberOfBounties); // Create new conditional payment in master contract: Master master = Master(masterAddress); address newConditionalPayment = master.createConditionalPayment.value(msg.value)( msg.sender, long, dueDate, strikePrice ); // Attribute conditional payment to creator creatorsConditionalPaymentAddress[msg.sender] = newConditionalPayment; }
0.5.8