comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Withdraws funds from the Compound pool. * @param erc20Contract The ERC20 contract address of the token to be withdrawn. * @param amount The amount of tokens to be withdrawn. */
function withdraw(address erc20Contract, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract)); uint256 redeemResult = cErc20.redeemUnderlying(amount); require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0."); }
0.5.17
/** * @dev Withdraws all funds from the Compound pool. * @param erc20Contract The ERC20 contract address of the token to be withdrawn. * @return Boolean indicating success. */
function withdrawAll(address erc20Contract) external returns (bool) { CErc20 cErc20 = CErc20(getCErc20Contract(erc20Contract)); uint256 balance = cErc20.balanceOf(address(this)); if (balance <= 0) return false; uint256 redeemResult = cErc20.redeem(balance); require(redeemResult == 0, "Error calling redeem on Compound cToken: error code not equal to 0."); return true; }
0.5.17
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator. /// @param transaction 0x transaction structure. /// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash) internal pure returns (bytes32 transactionHash) { // Hash the transaction with the domain separator of the Exchange contract. transactionHash = LibEIP712.hashEIP712Message( eip712ExchangeDomainHash, transaction.getStructHash() ); return transactionHash; }
0.5.17
/// @dev Calculates EIP712 hash of the 0x transaction struct. /// @param transaction 0x transaction structure. /// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction) internal pure returns (bytes32 result) { bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH; bytes memory data = transaction.data; uint256 salt = transaction.salt; uint256 expirationTimeSeconds = transaction.expirationTimeSeconds; uint256 gasPrice = transaction.gasPrice; address signerAddress = transaction.signerAddress; // Assembly for more efficiently computing: // result = keccak256(abi.encodePacked( // schemaHash, // salt, // expirationTimeSeconds, // gasPrice, // uint256(signerAddress), // keccak256(data) // )); assembly { // Compute hash of data let dataHash := keccak256(add(data, 32), mload(data)) // Load free memory pointer let memPtr := mload(64) mstore(memPtr, schemaHash) // hash of schema mstore(add(memPtr, 32), salt) // salt mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds mstore(add(memPtr, 96), gasPrice) // gasPrice mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress mstore(add(memPtr, 160), dataHash) // hash of data // Compute hash result := keccak256(memPtr, 192) } return result; }
0.5.17
/** * @dev Market sells to 0x exchange orders up to a certain amount of input. * @param orders The limit orders to be filled in ascending order of price. * @param signatures The signatures for the orders. * @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees). * @param protocolFee The protocol fee in ETH to pay to 0x. * @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought). */
function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) public returns (uint256[2] memory) { require(orders.length > 0, "At least one order and matching signature is required."); require(orders.length == signatures.length, "Mismatch between number of orders and signatures."); require(takerAssetFillAmount > 0, "Taker asset fill amount must be greater than 0."); LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures); return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount]; }
0.5.17
/// @dev Calculates partial value given a numerator and denominator rounded down. /// Reverts if rounding error is >= 0.1% /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to calculate partial of. /// @return Partial value of target rounded down.
function safeGetPartialAmountFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256 partialAmount) { if (isRoundingErrorFloor( numerator, denominator, target )) { LibRichErrors.rrevert(LibMathRichErrors.RoundingError( numerator, denominator, target )); } partialAmount = numerator.safeMul(target).safeDiv(denominator); return partialAmount; }
0.5.17
/// @dev Checks if rounding error >= 0.1% when rounding up. /// @param numerator Numerator. /// @param denominator Denominator. /// @param target Value to multiply with numerator/denominator. /// @return Rounding error is present.
function isRoundingErrorCeil( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { if (denominator == 0) { LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError()); } // See the comments in `isRoundingError`. if (target == 0 || numerator == 0) { // When either is zero, the ideal value and rounded value are zero // and there is no rounding error. (Although the relative error // is undefined.) return false; } // Compute remainder as before uint256 remainder = mulmod( target, numerator, denominator ); remainder = denominator.safeSub(remainder) % denominator; isError = remainder.safeMul(1000) >= numerator.safeMul(target); return isError; }
0.5.17
// Returns how much a user could earn plus the giving block number.
function takeWithBlock() external override view returns (uint, uint) { if(mintCumulation >= maxMintCumulation) return (0, block.number); UserInfo storage userInfo = users[msg.sender]; uint _accAmountPerShare = accAmountPerShare; // uint256 lpSupply = totalProductivity; if (block.number > lastRewardBlock && totalProductivity != 0) { uint multiplier = block.number.sub(lastRewardBlock); uint reward = multiplier.mul(wasabiPerBlock); _accAmountPerShare = _accAmountPerShare.add(reward.mul(1e12).div(totalProductivity)); } return (userInfo.amount.mul(_accAmountPerShare).div(1e12).sub(userInfo.rewardDebt), block.number); }
0.6.8
/** * @dev Returns a token's yVault contract address given its ERC20 contract address. * @param erc20Contract The ERC20 contract address of the token. */
function getYVaultContract(address erc20Contract) private pure returns (address) { if (erc20Contract == 0x6B175474E89094C44Da98b954EedeAC495271d0F) return 0xACd43E627e64355f1861cEC6d3a6688B31a6F952; // DAI => DAI yVault if (erc20Contract == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) return 0x597aD1e0c13Bfe8025993D9e79C69E1c0233522e; // USDC => USDC yVault if (erc20Contract == 0xdAC17F958D2ee523a2206206994597C13D831ec7) return 0x2f08119C6f07c006695E079AAFc638b8789FAf18; // USDT => USDT yVault if (erc20Contract == 0x0000000000085d4780B73119b644AE5ecd22b376) return 0x37d19d1c4E1fa9DC47bD1eA12f742a0887eDa74a; // TUSD => TUSD yVault else revert("Supported yearn.finance yVault address not found for this token address."); }
0.5.17
/** * @dev Withdraws funds from the yVault. * @param erc20Contract The ERC20 contract address of the token to be withdrawn. * @param amount The amount of tokens to be withdrawn. */
function withdraw(address erc20Contract, uint256 amount) external { require(amount > 0, "Amount must be greater than 0."); IVault yVault = IVault(getYVaultContract(erc20Contract)); uint256 pricePerFullShare = yVault.getPricePerFullShare(); uint256 shares = amount.mul(1e18).div(pricePerFullShare); if (shares.mul(pricePerFullShare).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder) yVault.withdraw(shares); }
0.5.17
/** * @dev sets 0 initial tokens, the owner, the supplyController, * the fee controller and fee recipient. * this serves as the constructor for the proxy but compiles to the * memory model of the Implementation contract. */
function initialize() public { require(!initialized, "already initialized"); owner = msg.sender; balances[owner] = totalSupply_; emit Transfer(address(0), owner, totalSupply_); proposedOwner = address(0); assetProtectionRole = address(0); supplyController = msg.sender; initializeDomainSeparator(); initialized = true; }
0.4.26
/** * @dev Transfer token to a specified address from msg.sender * Transfer additionally sends the fee to the fee controller * Note: the use of Safemath ensures that _value is nonnegative. * @param _to The address to transfer to. * @param _value The amount to be transferred. */
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0), "cannot transfer to address zero"); require(!frozen[_to] && !frozen[msg.sender], "address frozen"); require(_value <= balances[msg.sender], "insufficient funds"); _transfer(msg.sender, _to, _value); return true; }
0.4.26
/** * @dev Allows the current owner or proposed owner to cancel transferring control of the contract to a proposedOwner */
function disregardProposeOwner() public { require(msg.sender == proposedOwner || msg.sender == owner, "only proposedOwner or owner"); require(proposedOwner != address(0), "can only disregard a proposed owner that was previously set"); address _oldProposedOwner = proposedOwner; proposedOwner = address(0); emit OwnershipTransferDisregarded(_oldProposedOwner); }
0.4.26
/** * @dev Performs a transfer on behalf of the from address, identified by its signature on the delegatedTransfer msg. * Splits a signature byte array into r,s,v for convenience. * @param sig the signature of the delgatedTransfer msg. * @param to The address to transfer to. * @param value The amount to be transferred. * @param serviceFee an optional ERC20 service fee paid to the executor of betaDelegatedTransfer by the from address. * @param seq a sequencing number included by the from address specific to this contract to protect from replays. * @param deadline a block number after which the pre-signed transaction has expired. * @return A boolean that indicates if the operation was successful. */
function betaDelegatedTransfer( bytes memory sig, address to, uint256 value, uint256 serviceFee, uint256 seq, uint256 deadline ) public returns (bool) { require(sig.length == 65, "signature should have length 65"); bytes32 r; bytes32 s; uint8 v; assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } require(_betaDelegatedTransfer(r, s, v, to, value, serviceFee, seq, deadline), "failed transfer"); return true; }
0.4.26
/** * @dev Performs an atomic batch of transfers on behalf of the from addresses, identified by their signatures. * Lack of nested array support in arguments requires all arguments to be passed as equal size arrays where * delegated transfer number i is the combination of all arguments at index i * @param r the r signatures of the delgatedTransfer msg. * @param s the s signatures of the delgatedTransfer msg. * @param v the v signatures of the delgatedTransfer msg. * @param to The addresses to transfer to. * @param value The amounts to be transferred. * @param serviceFee optional ERC20 service fees paid to the delegate of betaDelegatedTransfer by the from address. * @param seq sequencing numbers included by the from address specific to this contract to protect from replays. * @param deadline block numbers after which the pre-signed transactions have expired. * @return A boolean that indicates if the operation was successful. */
function betaDelegatedTransferBatch( bytes32[] r, bytes32[] s, uint8[] v, address[] to, uint256[] value, uint256[] serviceFee, uint256[] seq, uint256[] deadline ) public returns (bool) { require(r.length == s.length && r.length == v.length && r.length == to.length && r.length == value.length, "length mismatch"); require(r.length == serviceFee.length && r.length == seq.length && r.length == deadline.length, "length mismatch"); for (uint i = 0; i < r.length; i++) { require( _betaDelegatedTransfer(r[i], s[i], v[i], to[i], value[i], serviceFee[i], seq[i], deadline[i]), "failed transfer" ); } return true; }
0.4.26
/// @dev Calculates amounts filled and fees paid by maker and taker. /// @param order to be filled. /// @param takerAssetFilledAmount Amount of takerAsset that will be filled. /// @param protocolFeeMultiplier The current protocol fee of the exchange contract. /// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue /// to be pure rather than view. /// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amounts fillResults.takerAssetFilledAmount = takerAssetFilledAmount; fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerAssetAmount ); fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.makerFee ); fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor( takerAssetFilledAmount, order.takerAssetAmount, order.takerFee ); // Compute the protocol fee that should be paid for a single fill. fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier); return fillResults; }
0.5.17
/// @dev Adds properties of both FillResults instances. /// @param fillResults1 The first FillResults. /// @param fillResults2 The second FillResults. /// @return The sum of both fill results.
function addFillResults( FillResults memory fillResults1, FillResults memory fillResults2 ) internal pure returns (FillResults memory totalFillResults) { totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount); totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount); totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid); totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid); totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid); return totalFillResults; }
0.5.17
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. Both orders will be fully filled in this /// case. /// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled. /// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { // Calculate the fully filled results for both orders. matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining; matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; return matchedFillResults; }
0.5.17
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results /// to the fillResults that are being collected on the order. /// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts /// can be derived from this order and the right asset remaining fields. /// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled. /// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled. /// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining; matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining; matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining; // Round down to ensure the left maker's exchange rate does not exceed the price specified by the order. // We favor the left maker when the exchange rate must be rounded and the profit is being paid in the // left maker asset. matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor( leftOrder.makerAssetAmount, leftOrder.takerAssetAmount, rightMakerAssetAmountRemaining ); return matchedFillResults; }
0.5.17
/** * Transfer tokens from the caller to a new holder. * No fee with this transfer */
function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // exchange tokens tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; }
0.4.21
//======================================ACTION CALLS=========================================//
function _stake(uint256 _amount) internal { require(stakingEnabled, "Staking not yet initialized"); require(IERC20(UniswapV2).balanceOf(msg.sender) >= _amount, "Insufficient SWAP AFT balance"); require(frozenOf(msg.sender) + _amount >= MINIMUM_STAKE, "Your amount is lower than the minimum amount allowed to stake"); require(IERC20(UniswapV2).allowance(msg.sender, address(this)) >= _amount, "Not enough allowance given to contract yet to spend by user"); info.users[msg.sender].staketime = now; info.totalFrozen += _amount; info.users[msg.sender].frozen += _amount; info.users[msg.sender].scaledPayout += int256(_amount * info.scaledPayoutPerToken); IERC20(UniswapV2).transferFrom(msg.sender, address(this), _amount); // Transfer liquidity tokens from the sender to this contract emit StakeEvent(msg.sender, address(this), _amount); }
0.6.4
/** * @dev Mint xU3LP tokens by sending *amount* of *inputAsset* tokens */
function mintWithToken(uint8 inputAsset, uint256 amount) external notLocked(msg.sender) whenNotPaused() { require(amount > 0); lock(msg.sender); checkTwap(); uint256 fee = Utils.calculateFee(amount, feeDivisors.mintFee); if (inputAsset == 0) { token0.safeTransferFrom(msg.sender, address(this), amount); _incrementWithdrawableToken0Fees(fee); _mintInternal( getToken0AmountInWei(getAmountInAsset1Terms(amount).sub(fee)) ); } else { token1.safeTransferFrom(msg.sender, address(this), amount); _incrementWithdrawableToken1Fees(fee); _mintInternal( getToken1AmountInWei(getAmountInAsset0Terms(amount).sub(fee)) ); } }
0.7.6
/** * @dev Burn *amount* of xU3LP tokens to receive proportional * amount of *outputAsset* tokens */
function burn(uint8 outputAsset, uint256 amount) external notLocked(msg.sender) { require(amount > 0); lock(msg.sender); checkTwap(); uint256 bufferBalance = getBufferBalance(); uint256 totalBalance = bufferBalance.add(getStakedBalance()); uint256 proRataBalance; if (outputAsset == 0) { proRataBalance = (totalBalance.mul(getAmountInAsset0Terms(amount))) .div(totalSupply()); } else { proRataBalance = ( totalBalance.mul(getAmountInAsset1Terms(amount)).div( totalSupply() ) ); } // Add swap slippage to the calculations uint256 proRataBalanceWithSlippage = proRataBalance.add(proRataBalance.div(SWAP_SLIPPAGE)); require( proRataBalanceWithSlippage <= bufferBalance, "Insufficient exit liquidity" ); super._burn(msg.sender, amount); // Fee is in wei (18 decimals, so doesn't need to be normalized) uint256 fee = Utils.calculateFee(proRataBalance, feeDivisors.burnFee); if (outputAsset == 0) { withdrawableToken0Fees = withdrawableToken0Fees.add(fee); } else { withdrawableToken1Fees = withdrawableToken1Fees.add(fee); } uint256 transferAmount = proRataBalance.sub(fee); transferOnBurn(outputAsset, transferAmount); }
0.7.6
// Get wanted xU3LP contract token balance - 5% of NAV
function getTargetBufferTokenBalance() public view returns (uint256 amount0, uint256 amount1) { (uint256 bufferAmount0, uint256 bufferAmount1) = getBufferTokenBalance(); (uint256 poolAmount0, uint256 poolAmount1) = getStakedTokenBalance(); amount0 = bufferAmount0.add(poolAmount0).div(BUFFER_TARGET); amount1 = bufferAmount1.add(poolAmount1).div(BUFFER_TARGET); // Keep 50:50 ratio amount0 = amount0.add(amount1).div(2); amount1 = amount0; }
0.7.6
/** * Check if token amounts match before attempting mint() or burn() * Uniswap contract requires deposits at a precise token ratio * If they don't match, swap the tokens so as to deposit as much as possible */
function checkIfAmountsMatchAndSwap( uint256 amount0ToMint, uint256 amount1ToMint ) private returns (uint256 amount0, uint256 amount1) { (uint256 amount0Minted, uint256 amount1Minted) = calculatePoolMintedAmounts(amount0ToMint, amount1ToMint); if ( amount0Minted < amount0ToMint.sub(amount0ToMint.div(MINT_BURN_SLIPPAGE)) || amount1Minted < amount1ToMint.sub(amount1ToMint.div(MINT_BURN_SLIPPAGE)) ) { // calculate liquidity ratio uint256 mintLiquidity = getLiquidityForAmounts(amount0ToMint, amount1ToMint); uint256 poolLiquidity = getPoolLiquidity(); int128 liquidityRatio = poolLiquidity == 0 ? 0 : int128(ABDKMath64x64.divuu(mintLiquidity, poolLiquidity)); (amount0, amount1) = restoreTokenRatios( amount0ToMint, amount1ToMint, amount0Minted, amount1Minted, liquidityRatio ); } else { (amount0, amount1) = (amount0ToMint, amount1ToMint); } }
0.7.6
// Migrate the current position to a new position with different ticks
function migratePosition(int24 newTickLower, int24 newTickUpper) external onlyOwnerOrManager { require(newTickLower != tickLower || newTickUpper != tickUpper); // withdraw entire liquidity from the position (uint256 _amount0, uint256 _amount1) = withdrawAll(); // burn current position NFT positionManager.burn(tokenId); tokenId = 0; // set new ticks and prices tickLower = newTickLower; tickUpper = newTickUpper; priceLower = TickMath.getSqrtRatioAtTick(newTickLower); priceUpper = TickMath.getSqrtRatioAtTick(newTickUpper); // if amounts don't add up when minting, swap tokens (uint256 amount0, uint256 amount1) = checkIfAmountsMatchAndSwap(_amount0, _amount1); // mint the position NFT and deposit the liquidity // set new NFT token id tokenId = createPosition(amount0, amount1); emit PositionMigrated(newTickLower, newTickUpper); }
0.7.6
/** * Transfers asset amount when user calls burn() * If there's not enough balance of that asset, * triggers a router swap to increase the balance * keep token ratio in xU3LP at 50:50 after swapping */
function transferOnBurn(uint8 outputAsset, uint256 transferAmount) private { (uint256 balance0, uint256 balance1) = getBufferTokenBalance(); if (outputAsset == 0) { if (balance0 < transferAmount) { uint256 amountIn = transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub( balance0 ); uint256 amountOut = transferAmount.sub(balance0); uint256 balanceFactor = Utils.sub0(balance1, amountOut).div(2); amountIn = amountIn.add(balanceFactor); amountOut = amountOut.add(balanceFactor); swapToken1ForToken0(amountIn, amountOut); } transferAmount = getToken0AmountInNativeDecimals(transferAmount); token0.safeTransfer(msg.sender, transferAmount); } else { if (balance1 < transferAmount) { uint256 amountIn = transferAmount.add(transferAmount.div(SWAP_SLIPPAGE)).sub( balance1 ); uint256 amountOut = transferAmount.sub(balance1); uint256 balanceFactor = Utils.sub0(balance0, amountOut).div(2); amountIn = amountIn.add(balanceFactor); amountOut = amountOut.add(balanceFactor); swapToken0ForToken1(amountIn, amountOut); } transferAmount = getToken1AmountInNativeDecimals(transferAmount); token1.safeTransfer(msg.sender, transferAmount); } }
0.7.6
/** * Mint function which initializes the pool position * Must be called before any liquidity can be deposited */
function mintInitial(uint256 amount0, uint256 amount1) external onlyOwnerOrManager { require(tokenId == 0); require(amount0 > 0 || amount1 > 0); checkTwap(); if (amount0 > 0) { token0.safeTransferFrom(msg.sender, address(this), amount0); } if (amount1 > 0) { token1.safeTransferFrom(msg.sender, address(this), amount1); } tokenId = createPosition(amount0, amount1); amount0 = getToken0AmountInWei(amount0); amount1 = getToken1AmountInWei(amount1); _mintInternal( getAmountInAsset1Terms(amount0).add(getAmountInAsset0Terms(amount1)) ); emit PositionInitialized(tickLower, tickUpper); }
0.7.6
/** * Creates the NFT token representing the pool position */
function createPosition(uint256 amount0, uint256 amount1) private returns (uint256 _tokenId) { (_tokenId, , , ) = positionManager.mint( INonfungiblePositionManager.MintParams({ token0: address(token0), token1: address(token1), fee: POOL_FEE, tickLower: tickLower, tickUpper: tickUpper, amount0Desired: amount0, amount1Desired: amount1, amount0Min: amount0.sub(amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: amount1.sub(amount1.div(MINT_BURN_SLIPPAGE)), recipient: address(this), deadline: block.timestamp }) ); }
0.7.6
/** * @dev Unstakes a given amount of liquidity from the Uni V3 position * @param liquidity amount of liquidity to unstake * @return amount0 token0 amount unstaked * @return amount1 token1 amount unstaked */
function unstakePosition(uint128 liquidity) private returns (uint256 amount0, uint256 amount1) { (uint256 _amount0, uint256 _amount1) = getAmountsForLiquidity(liquidity); (amount0, amount1) = positionManager.decreaseLiquidity( INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId: tokenId, liquidity: liquidity, amount0Min: _amount0.sub(_amount0.div(MINT_BURN_SLIPPAGE)), amount1Min: _amount1.sub(_amount1.div(MINT_BURN_SLIPPAGE)), deadline: block.timestamp }) ); }
0.7.6
/* * Withdraw function for token0 and token1 fees */
function withdrawFees() external onlyOwnerOrManager { uint256 token0Fees = getToken0AmountInNativeDecimals(withdrawableToken0Fees); uint256 token1Fees = getToken1AmountInNativeDecimals(withdrawableToken1Fees); if (token0Fees > 0) { token0.safeTransfer(msg.sender, token0Fees); withdrawableToken0Fees = 0; } if (token1Fees > 0) { token1.safeTransfer(msg.sender, token1Fees); withdrawableToken1Fees = 0; } emit FeeWithdraw(token0Fees, token1Fees); }
0.7.6
/** * @dev Withdraw until token0 or token1 balance reaches amount * @param forToken0 withdraw balance for token0 (true) or token1 (false) * @param amount minimum amount we want to have in token0 or token1 */
function withdrawSingleToken(bool forToken0, uint256 amount) private { uint256 balance; uint256 unstakeAmount0; uint256 unstakeAmount1; uint256 swapAmount; do { // calculate how much we can withdraw (unstakeAmount0, unstakeAmount1) = calculatePoolMintedAmounts( getToken0AmountInNativeDecimals(amount), getToken1AmountInNativeDecimals(amount) ); // withdraw both tokens _unstake(unstakeAmount0, unstakeAmount1); // swap the excess amount of token0 for token1 or vice-versa swapAmount = forToken0 ? getToken1AmountInWei(unstakeAmount1) : getToken0AmountInWei(unstakeAmount0); forToken0 ? swapToken1ForToken0( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount ) : swapToken0ForToken1( swapAmount.add(swapAmount.div(SWAP_SLIPPAGE)), swapAmount ); balance = forToken0 ? getBufferToken0Balance() : getBufferToken1Balance(); } while (balance < amount); }
0.7.6
// Returns the earliest oracle observation time
function getObservationTime() public view returns (uint32) { (, , uint16 index, uint16 cardinality, , , ) = pool.slot0(); uint16 oldestObservationIndex = (index + 1) % cardinality; (uint32 observationTime, , , bool initialized) = pool.observations(oldestObservationIndex); if (!initialized) (observationTime, , , ) = pool.observations(0); return observationTime; }
0.7.6
/** * Get asset 0 twap * Uses Uni V3 oracle, reading the TWAP from twap period * or the earliest oracle observation time if twap period is not set */
function getAsset0Price() public view returns (int128) { uint32[] memory secondsArray = new uint32[](2); // get earliest oracle observation time uint32 observationTime = getObservationTime(); uint32 currTimestamp = uint32(block.timestamp); uint32 earliestObservationSecondsAgo = currTimestamp - observationTime; if ( twapPeriod == 0 || !Utils.lte( currTimestamp, observationTime, currTimestamp - twapPeriod ) ) { // set to earliest observation time if: // a) twap period is 0 (not set) // b) now - twap period is before earliest observation secondsArray[0] = earliestObservationSecondsAgo; } else { secondsArray[0] = twapPeriod; } secondsArray[1] = 0; (int56[] memory prices, ) = pool.observe(secondsArray); int128 twap = Utils.getTWAP(prices, secondsArray[0]); if (token1Decimals > token0Decimals) { // divide twap by token decimal difference twap = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, tokenDiffDecimalMultiplier) ); } else if (token0Decimals > token1Decimals) { // multiply twap by token decimal difference int128 multiplierFixed = ABDKMath64x64.fromUInt(tokenDiffDecimalMultiplier); twap = ABDKMath64x64.mul(twap, multiplierFixed); } return twap; }
0.7.6
/** * Checks if twap deviates too much from the previous twap */
function checkTwap() private { int128 twap = getAsset0Price(); int128 _lastTwap = lastTwap; int128 deviation = _lastTwap > twap ? _lastTwap - twap : twap - _lastTwap; int128 maxDeviation = ABDKMath64x64.mul( twap, ABDKMath64x64.divu(1, maxTwapDeviationDivisor) ); require(deviation <= maxDeviation, "Wrong twap"); lastTwap = twap; }
0.7.6
// ========= ENTER ==========
function enter() public timeBoundsCheck { require(action == ACTION.ENTER, "Wrong action"); require(!completed, "Action completed"); uint256 ugasReserves; uint256 wethReserves; (wethReserves,ugasReserves, ) = uniswap_pair.getReserves(); require( withinBounds(wethReserves, ugasReserves), "Market rate is outside bounds" ); uint256 wethBalance = 300 * (10**18); // Since we are aiming for a CR of 4, we can mint with up to 80% of reserves // We mint slightly less so we can be sure there will be enough WETH uint256 collateral_amount = (wethBalance * 79) / 100; uint256 mint_amount = (collateral_amount * ugasReserves) / wethReserves / 4; _mint(collateral_amount, mint_amount); _mintLPToken(uniswap_pair, WETH, UGAS, mint_amount, RESERVES); completed = true; }
0.5.15
// ========== EXIT ==========
function exit() public timeBoundsCheck { require(action == ACTION.EXIT); require(!completed, "Action completed"); uint256 ugasReserves; uint256 wethReserves; (wethReserves,ugasReserves, ) = uniswap_pair.getReserves(); require( withinBounds(wethReserves, ugasReserves), "Market rate is outside bounds" ); _burnLPToken(uniswap_pair, address(this)); _repayAndWithdraw(); WETH.transfer(RESERVES, WETH.balanceOf(address(this))); uint256 ugasBalance = UGAS.balanceOf(address(this)); if (ugasBalance > 0) { UGAS.transfer(RESERVES, ugasBalance); } completed = true; }
0.5.15
// ------------------------------------------------------------------------------------------------------- // CANCELLATION FUNCTIONS --------------------------------------------------------------------------------
function calculateCancel(Booking storage booking) internal view returns (bool isPossible, uint depositToHostPpm, uint cleaningToHostPpm, uint priceToHostPpm) { // initialization isPossible = false; IBooking.Status currentStatus = getStatus(booking); (uint nightsAlreadyOccupied, uint nightsTotal) = getNights(booking); // checking if ((currentStatus != IBooking.Status.Booked && currentStatus != IBooking.Status.Started) || (nightsTotal == 0 || nightsAlreadyOccupied >= nightsTotal) || (currentStatus == IBooking.Status.Started && msg.sender == booking.host)) { return (false, 0, 0, 0); } depositToHostPpm = 0; cleaningToHostPpm = nightsAlreadyOccupied == 0 ? 0 : 1000000; priceToHostPpm = currentStatus == IBooking.Status.Booked && (msg.sender == booking.host || msg.sender == booking.feeBeneficiary) ? 0 : getPriceToHostPpmByCancellationPolicy(booking, nightsAlreadyOccupied, nightsTotal, now); isPossible = true; }
0.5.6
// ------------------------------------------------------------------------------------------------------- // FUNCTIONS THAT SPLIT ALL BALANCE AND RETURN MONEY TO THE GUEST ----------------------------------------
function splitAllBalance(Booking storage booking, uint depositToHostPpm, uint cleaningToHostPpm, uint priceToHostPpm) internal { uint priceToHost = booking.price * priceToHostPpm / 1000000; uint depositToHost = booking.deposit * depositToHostPpm / 1000000; uint cleaningToHost = booking.cleaning * cleaningToHostPpm / 1000000; booking.hostWithdrawAllowance = priceToHost + cleaningToHost + depositToHost; booking.guestWithdrawAllowance = (booking.price - priceToHost) + (booking.deposit - depositToHost) + (booking.cleaning - cleaningToHost); }
0.5.6
// HELPERS FOR SPLITTING FUNDS ---------------------------------------------------------------------------
function getNights(Booking storage booking) internal view returns (uint nightsAlreadyOccupied, uint nightsTotal) { nightsTotal = (12 * 60 * 60 + booking.dateTo - booking.dateFrom) / (24 * 60 * 60); if (now <= booking.dateFrom) { nightsAlreadyOccupied = 0; } else { // first night is occupied when 1 second is passed after check-in, and so on nightsAlreadyOccupied = (24 * 60 * 60 - 1 + now - booking.dateFrom) / (24 * 60 * 60); } if (nightsAlreadyOccupied > nightsTotal) { nightsAlreadyOccupied = nightsTotal; } }
0.5.6
/** * An address can become a new seller only in case it has no tokens. * This is required to prevent stealing of tokens from newSeller via * 2 calls of this function. */
function changeSeller(address newSeller) onlyOwner public returns (bool) { require(newSeller != address(0)); require(seller != newSeller); // To prevent stealing of tokens from newSeller via 2 calls of changeSeller: require(balances[newSeller] == 0); address oldSeller = seller; uint256 unsoldTokens = balances[oldSeller]; balances[oldSeller] = 0; balances[newSeller] = unsoldTokens; emit Transfer(oldSeller, newSeller, unsoldTokens); seller = newSeller; emit ChangeSellerEvent(oldSeller, newSeller); return true; }
0.4.25
// For Owner & Manager
function createMatch(uint _id, string _team, string _teamDetail, int32 _pointSpread, uint64 _startTime, uint64 _endTime) onlyOwner public { require(_startTime < _endTime); require(matches[_id].created == false); // Create new match Match memory _match = Match({ created:true, team: _team, teamDetail: _teamDetail, pointSpread: _pointSpread, startTime: _startTime, endTime: _endTime, stakesOfWin: 0, stakesOfDraw: 0, stakesOfLoss: 0, result: Result.Unknown }); // Insert into matches matches[_id] = _match; numMatches++; // Set event emit NewMatch(_id, _team, _teamDetail, _pointSpread, _startTime, _endTime); }
0.4.24
// For Player
function bet(uint _id, Result _result) validId(_id) validResult(_result) public payable { // Check value require(msg.value > 0); // Check match state Match storage _match = matches[_id]; require(_match.result == Result.Unknown); require(_match.startTime <= now); require(_match.endTime >= now); // Update matches if (_result == Result.HomeWin) { _match.stakesOfWin = add(_match.stakesOfWin, msg.value); } else if (_result == Result.HomeDraw) { _match.stakesOfDraw = add(_match.stakesOfDraw, msg.value); } else if (_result == Result.HomeLoss) { _match.stakesOfLoss = add(_match.stakesOfLoss, msg.value); } // Update predictions Prediction storage _prediction = predictions[_id][msg.sender]; if (_prediction.result == Result.Unknown) { _prediction.stake = msg.value; _prediction.result = _result; } else { require(_prediction.result == _result); _prediction.stake = add(_prediction.stake, msg.value); } // Set event emit Bet(msg.sender, _id, _result, msg.value, _match.stakesOfWin, _match.stakesOfDraw, _match.stakesOfLoss); }
0.4.24
//addMembers is adding members to the contract
function addMembers(address[] memory members, uint256[3][] memory membersTokens) external onlyOwner returns (bool) { require (members.length == membersTokens.length, "ClinTex: arrays of incorrect length"); for (uint256 index = 0; index < members.length; index++){ require(membersTokens[index][0] >= membersTokens[index][1], "ClinTex: there are more frozen tokens before the first date than on the balance"); require(membersTokens[index][0] >= membersTokens[index][2], "ClinTex: there are more frozen tokens before the second date than on the balance"); _mint(members[index], membersTokens[index][0]); _freezeTokens[members[index]].frozenTokensBeforeTheFirstDate = membersTokens[index][1]; _freezeTokens[members[index]].frozenTokensBeforeTheSecondDate = membersTokens[index][2]; } return true; }
0.8.7
//getFreezeTokens returns the number of frozen tokens on the account
function getFreezeTokens(address account, uint8 flag) public view returns (uint256) { require(account != address(0), "ClinTex: address must not be empty"); require (flag < 2, "ClinTex: unknown flag"); if (flag == 0) { return _freezeTokens[account].frozenTokensBeforeTheFirstDate; } return _freezeTokens[account].frozenTokensBeforeTheSecondDate; }
0.8.7
// Returns the number of naps token to boost
function calculateCost(uint256 level) public view returns(uint256) { uint256 cycles = calculateCycle.calculate(deployedTime,block.timestamp,napsDiscountRange); // Cap it to 5 times if(cycles > 5) { cycles = 5; } // // cost = initialCost * (0.9)^cycles = initial cost * (9^cycles)/(10^cycles) if (level == 1) { return napsLevelOneCost.mul(9 ** cycles).div(10 ** cycles); }else if(level == 2) { return napsLevelTwoCost.mul(9 ** cycles).div(10 ** cycles); }else if(level ==3) { return napsLevelThreeCost.mul(9 ** cycles).div(10 ** cycles); } }
0.6.0
//isTransferFreezeTokens returns true when transferring frozen tokens
function isTransferFreezeTokens(address account, uint256 amount) public view returns (bool) { if (block.timestamp > _secondUnfreezeDate){ return false; } if (_firstUnfreezeDate < block.timestamp && block.timestamp < _secondUnfreezeDate) { if (balanceOf(account) - getFreezeTokens(account, 1) < amount) { return true; } } if (block.timestamp < _firstUnfreezeDate) { if (balanceOf(account) - getFreezeTokens(account, 0) < amount) { return true; } } return false; }
0.8.7
/** * This is the function that burns the MAHA and returns how much ARTH should * actually be spent. * * Note we are always selling tokenA. */
function conductChecks( uint112 reserveA, uint112 reserveB, uint256 priceALast, uint256 priceBLast, uint256 amountOutA, uint256 amountOutB, uint256 amountInA, uint256 amountInB, address from, address to ) external override onlyPair { // The to nd from address has to be whitelisted. require(whitelist[to], "ArthIncentiveControllerV2: FORBIDDEN"); require(whitelist[from], "ArthIncentiveControllerV2: FORBIDDEN"); }
0.8.0
/** * @dev Initializer that sets supported ERC20 contract addresses and supported pools for each supported token. */
function initialize() public initializer { // Initialize base contracts Ownable.initialize(msg.sender); // Add supported currencies addSupportedCurrency("DAI", 0x6B175474E89094C44Da98b954EedeAC495271d0F, 18); addPoolToCurrency("DAI", RariFundController.LiquidityPool.dYdX); addPoolToCurrency("DAI", RariFundController.LiquidityPool.Compound); addPoolToCurrency("DAI", RariFundController.LiquidityPool.Aave); addPoolToCurrency("DAI", RariFundController.LiquidityPool.yVault); addSupportedCurrency("USDC", 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 6); addPoolToCurrency("USDC", RariFundController.LiquidityPool.dYdX); addPoolToCurrency("USDC", RariFundController.LiquidityPool.Compound); addPoolToCurrency("USDC", RariFundController.LiquidityPool.Aave); addPoolToCurrency("USDC", RariFundController.LiquidityPool.yVault); addSupportedCurrency("USDT", 0xdAC17F958D2ee523a2206206994597C13D831ec7, 6); addPoolToCurrency("USDT", RariFundController.LiquidityPool.Compound); addPoolToCurrency("USDT", RariFundController.LiquidityPool.Aave); addPoolToCurrency("USDT", RariFundController.LiquidityPool.yVault); addSupportedCurrency("TUSD", 0x0000000000085d4780B73119b644AE5ecd22b376, 18); addPoolToCurrency("TUSD", RariFundController.LiquidityPool.Aave); addPoolToCurrency("TUSD", RariFundController.LiquidityPool.yVault); addSupportedCurrency("BUSD", 0x4Fabb145d64652a948d72533023f6E7A623C7C53, 18); addPoolToCurrency("BUSD", RariFundController.LiquidityPool.Aave); addSupportedCurrency("sUSD", 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51, 18); addPoolToCurrency("sUSD", RariFundController.LiquidityPool.Aave); addSupportedCurrency("mUSD", 0xe2f2a5C287993345a840Db3B0845fbC70f5935a5, 18); addPoolToCurrency("mUSD", RariFundController.LiquidityPool.mStable); // Initialize raw fund balance cache (can't set initial values in field declarations with proxy storage) _rawFundBalanceCache = -1; }
0.5.17
/** * @dev Upgrades RariFundManager. * Sends data to the new contract and sets the new RariFundToken minter. * @param newContract The address of the new RariFundManager contract. */
function upgradeFundManager(address newContract) external onlyOwner { require(fundDisabled, "This fund manager contract must be disabled before it can be upgraded."); // Pass data to the new contract FundManagerData memory data; data = FundManagerData( _netDeposits, _rawInterestAccruedAtLastFeeRateChange, _interestFeesGeneratedAtLastFeeRateChange, _interestFeesClaimed ); RariFundManager(newContract).setFundManagerData(data); // Update RariFundToken minter if (_rariFundTokenContract != address(0)) { rariFundToken.addMinter(newContract); rariFundToken.renounceMinter(); } emit FundManagerUpgraded(newContract); }
0.5.17
/** * @dev Upgrades RariFundManager. * Sets data receieved from the old contract. * @param data The data from the old contract necessary to initialize the new contract. */
function setFundManagerData(FundManagerData calldata data) external { require(_authorizedFundManagerDataSource != address(0) && msg.sender == _authorizedFundManagerDataSource, "Caller is not an authorized source."); _netDeposits = data.netDeposits; _rawInterestAccruedAtLastFeeRateChange = data.rawInterestAccruedAtLastFeeRateChange; _interestFeesGeneratedAtLastFeeRateChange = data.interestFeesGeneratedAtLastFeeRateChange; _interestFeesClaimed = data.interestFeesClaimed; _interestFeeRate = RariFundManager(_authorizedFundManagerDataSource).getInterestFeeRate(); _withdrawalFeeRate = RariFundManager(_authorizedFundManagerDataSource).getWithdrawalFeeRate(); }
0.5.17
/** * @dev Returns the fund controller's balance of the specified currency in the specified pool. * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state. * @param pool The index of the pool. * @param currencyCode The currency code of the token. */
function getPoolBalance(RariFundController.LiquidityPool pool, string memory currencyCode) internal returns (uint256) { if (!rariFundController.hasCurrencyInPool(pool, currencyCode)) return 0; if (_cachePoolBalances || _cacheDydxBalances) { if (pool == RariFundController.LiquidityPool.dYdX) { address erc20Contract = _erc20Contracts[currencyCode]; require(erc20Contract != address(0), "Invalid currency code."); if (_dydxBalancesCache.length == 0) (_dydxTokenAddressesCache, _dydxBalancesCache) = rariFundController.getDydxBalances(); for (uint256 i = 0; i < _dydxBalancesCache.length; i++) if (_dydxTokenAddressesCache[i] == erc20Contract) return _dydxBalancesCache[i]; revert("Failed to get dYdX balance of this currency code."); } else if (_cachePoolBalances) { uint8 poolAsUint8 = uint8(pool); if (_poolBalanceCache[currencyCode][poolAsUint8] == 0) _poolBalanceCache[currencyCode][poolAsUint8] = rariFundController._getPoolBalance(pool, currencyCode); return _poolBalanceCache[currencyCode][poolAsUint8]; } } return rariFundController._getPoolBalance(pool, currencyCode); }
0.5.17
/** * @notice Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of the specified currency. * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `RariFundController.getPoolBalance`) potentially modifies the state. * @param currencyCode The currency code of the balance to be calculated. */
function getRawFundBalance(string memory currencyCode) public returns (uint256) { address erc20Contract = _erc20Contracts[currencyCode]; require(erc20Contract != address(0), "Invalid currency code."); IERC20 token = IERC20(erc20Contract); uint256 totalBalance = token.balanceOf(_rariFundControllerContract); for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++) totalBalance = totalBalance.add(getPoolBalance(_poolsByCurrency[currencyCode][i], currencyCode)); return totalBalance; }
0.5.17
/** * @dev Returns the fund's raw total balance (all RFT holders' funds + all unclaimed fees) of all currencies in USD (scaled by 1e18). * Accepts prices in USD as a parameter to avoid calculating them every time. * Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state. */
function getRawFundBalance(uint256[] memory pricesInUsd) public cacheDydxBalances returns (uint256) { uint256 totalBalance = 0; for (uint256 i = 0; i < _supportedCurrencies.length; i++) { string memory currencyCode = _supportedCurrencies[i]; uint256 balance = getRawFundBalance(currencyCode); uint256 balanceUsd = balance.mul(pricesInUsd[i]).div(10 ** _currencyDecimals[currencyCode]); totalBalance = totalBalance.add(balanceUsd); } return totalBalance; }
0.5.17
/** * @notice Returns the total balance in USD (scaled by 1e18) of `account`. * @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getRawFundBalance`) potentially modifies the state. * @param account The account whose balance we are calculating. */
function balanceOf(address account) external returns (uint256) { uint256 rftTotalSupply = rariFundToken.totalSupply(); if (rftTotalSupply == 0) return 0; uint256 rftBalance = rariFundToken.balanceOf(account); uint256 fundBalanceUsd = getFundBalance(); uint256 accountBalanceUsd = rftBalance.mul(fundBalanceUsd).div(rftTotalSupply); return accountBalanceUsd; }
0.5.17
/** * @notice Returns an array of currency codes currently accepted for deposits. */
function getAcceptedCurrencies() external view returns (string[] memory) { uint256 arrayLength = 0; for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) arrayLength++; string[] memory acceptedCurrencies = new string[](arrayLength); uint256 index = 0; for (uint256 i = 0; i < _supportedCurrencies.length; i++) if (_acceptedCurrencies[_supportedCurrencies[i]]) { acceptedCurrencies[index] = _supportedCurrencies[i]; index++; } return acceptedCurrencies; }
0.5.17
/** * @dev Marks `currencyCodes` as accepted or not accepted. * @param currencyCodes The currency codes to mark as accepted or not accepted. * @param accepted An array of booleans indicating if each of `currencyCodes` is to be accepted. */
function setAcceptedCurrencies(string[] calldata currencyCodes, bool[] calldata accepted) external onlyRebalancer { require (currencyCodes.length > 0 && currencyCodes.length == accepted.length, "Lengths of arrays must be equal and both greater than 0."); for (uint256 i = 0; i < currencyCodes.length; i++) _acceptedCurrencies[currencyCodes[i]] = accepted[i]; }
0.5.17
/** * @dev Returns the amount of RFT to burn for a withdrawal (used by `_withdrawFrom`). * @param from The address from which RFT will be burned. * @param amountUsd The amount of the withdrawal in USD */
function getRftBurnAmount(address from, uint256 amountUsd) internal returns (uint256) { uint256 rftTotalSupply = rariFundToken.totalSupply(); uint256 fundBalanceUsd = getFundBalance(); require(fundBalanceUsd > 0, "Fund balance is zero."); uint256 rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd); require(rftAmount <= rariFundToken.balanceOf(from), "Your RFT balance is too low for a withdrawal of this amount."); require(rftAmount > 0, "Withdrawal amount is so small that no RFT would be burned."); return rftAmount; }
0.5.17
/** * @dev Internal function to withdraw funds from pools if necessary for `RariFundController` to hold at least `amount` of actual tokens. * This function was separated from `_withdrawFrom` to avoid the stack going too deep. * @param currencyCode The currency code of the token to be withdrawn. * @param amount The minimum amount of tokens that must be held by `RariFundController` after withdrawing. * @return The actual amount withdrawn after potential yVault withdrawal fees. */
function withdrawFromPoolsIfNecessary(string memory currencyCode, uint256 amount) internal returns (uint256) { // Check contract balance of token and withdraw from pools if necessary address erc20Contract = _erc20Contracts[currencyCode]; IERC20 token = IERC20(erc20Contract); uint256 contractBalance = token.balanceOf(_rariFundControllerContract); for (uint256 i = 0; i < _poolsByCurrency[currencyCode].length; i++) { if (contractBalance >= amount) break; RariFundController.LiquidityPool pool = _poolsByCurrency[currencyCode][i]; uint256 poolBalance = getPoolBalance(pool, currencyCode); if (poolBalance <= 0) continue; uint256 amountLeft = amount.sub(contractBalance); bool withdrawAll = amountLeft >= poolBalance; uint256 poolAmount = withdrawAll ? poolBalance : amountLeft; rariFundController.withdrawFromPoolOptimized(pool, currencyCode, poolAmount, withdrawAll); if (pool == RariFundController.LiquidityPool.dYdX) { for (uint256 j = 0; j < _dydxBalancesCache.length; j++) if (_dydxTokenAddressesCache[j] == erc20Contract) _dydxBalancesCache[j] = poolBalance.sub(poolAmount); } else _poolBalanceCache[currencyCode][uint8(pool)] = poolBalance.sub(poolAmount); contractBalance = contractBalance.add(poolAmount); } require(amount <= contractBalance, "Available balance not enough to cover amount even after withdrawing from pools."); uint256 realContractBalance = token.balanceOf(_rariFundControllerContract); return realContractBalance < amount ? realContractBalance : amount; }
0.5.17
/** * @dev Withdraws multiple currencies from the Rari Yield Pool to `msg.sender` (RariFundProxy) in exchange for RFT burned from `from`. * You may only withdraw currencies held by the fund (see `getRawFundBalance(string currencyCode)`). * Please note that you must approve RariFundManager to burn of the necessary amount of RFT. * @param from The address from which RFT will be burned. * @param currencyCodes The currency codes of the tokens to be withdrawn. * @param amounts The amounts of the tokens to be withdrawn. * @return Array of amounts withdrawn after fees. */
function withdrawFrom(address from, string[] calldata currencyCodes, uint256[] calldata amounts) external onlyProxy cachePoolBalances returns (uint256[] memory) { // Input validation require(currencyCodes.length > 0 && currencyCodes.length == amounts.length, "Lengths of currency code and amount arrays must be greater than 0 and equal."); uint256[] memory pricesInUsd = rariFundPriceConsumer.getCurrencyPricesInUsd(); // Manually cache raw fund balance (no need to check if set previously because the function is external) _rawFundBalanceCache = toInt256(getRawFundBalance(pricesInUsd)); // Make withdrawals uint256[] memory amountsAfterFees = new uint256[](currencyCodes.length); for (uint256 i = 0; i < currencyCodes.length; i++) amountsAfterFees[i] = _withdrawFrom(from, currencyCodes[i], amounts[i], pricesInUsd); // Reset _rawFundBalanceCache _rawFundBalanceCache = -1; // Return amounts withdrawn after fees return amountsAfterFees; }
0.5.17
/** * @dev Sets the fee rate on interest. * @param rate The proportion of interest accrued to be taken as a service fee (scaled by 1e18). */
function setInterestFeeRate(uint256 rate) external fundEnabled onlyOwner cacheRawFundBalance { require(rate != _interestFeeRate, "This is already the current interest fee rate."); require(rate <= 1e18, "The interest fee rate cannot be greater than 100%."); _depositFees(); _interestFeesGeneratedAtLastFeeRateChange = getInterestFeesGenerated(); // MUST update this first before updating _rawInterestAccruedAtLastFeeRateChange since it depends on it _rawInterestAccruedAtLastFeeRateChange = getRawInterestAccrued(); _interestFeeRate = rate; }
0.5.17
/** * @dev Internal function to deposit all accrued fees on interest back into the fund on behalf of the master beneficiary. * @return Integer indicating success (0), no fees to claim (1), or no RFT to mint (2). */
function _depositFees() internal fundEnabled cacheRawFundBalance returns (uint8) { // Input validation require(_interestFeeMasterBeneficiary != address(0), "Master beneficiary cannot be the zero address."); // Get and validate unclaimed interest fees uint256 amountUsd = getInterestFeesUnclaimed(); if (amountUsd <= 0) return 1; // Calculate RFT amount to mint and validate uint256 rftTotalSupply = rariFundToken.totalSupply(); uint256 rftAmount = 0; if (rftTotalSupply > 0) { uint256 fundBalanceUsd = getFundBalance(); if (fundBalanceUsd > 0) rftAmount = amountUsd.mul(rftTotalSupply).div(fundBalanceUsd); else rftAmount = amountUsd; } else rftAmount = amountUsd; if (rftAmount <= 0) return 2; // Update claimed interest fees and net deposits, mint RFT, emit events, and return no error _interestFeesClaimed = _interestFeesClaimed.add(amountUsd); _netDeposits = _netDeposits.add(int256(amountUsd)); require(rariFundToken.mint(_interestFeeMasterBeneficiary, rftAmount), "Failed to mint output tokens."); emit Deposit("USD", _interestFeeMasterBeneficiary, _interestFeeMasterBeneficiary, amountUsd, amountUsd, rftAmount); emit InterestFeeDeposit(_interestFeeMasterBeneficiary, amountUsd); // Update RGT distribution speeds updateRgtDistributionSpeeds(); // Return no error return 0; }
0.5.17
/** * @notice Deposits all accrued fees on interest back into the fund on behalf of the master beneficiary. * @return Boolean indicating success. */
function depositFees() external onlyRebalancer { uint8 result = _depositFees(); require(result == 0, result == 2 ? "Deposit amount is so small that no RFT would be minted." : "No new fees are available to claim."); }
0.5.17
/** * @dev Sets the withdrawal fee rate. * @param rate The proportion of every withdrawal taken as a service fee (scaled by 1e18). */
function setWithdrawalFeeRate(uint256 rate) external fundEnabled onlyOwner { require(rate != _withdrawalFeeRate, "This is already the current withdrawal fee rate."); require(rate <= 1e18, "The withdrawal fee rate cannot be greater than 100%."); _withdrawalFeeRate = rate; }
0.5.17
//=============================================================================================================== //=============================================================================================================== //=============================================================================================================== // Ownable removed as a lib and added here to allow for custom transfers and renouncements. // This allows for removal of ownership privileges from the owner once renounced or transferred.
function transferOwner(address newOwner) external onlyOwner { require(newOwner != address(0), "Call renounceOwnership to transfer owner to the zero address."); require(newOwner != DEAD, "Call renounceOwnership to transfer owner to the zero address."); setExcludedFromFees(_owner, false); setExcludedFromFees(newOwner, true); if(balanceOf(_owner) > 0) { _transfer(_owner, newOwner, balanceOf(_owner)); } _owner = newOwner; emit OwnershipTransferred(_owner, newOwner); }
0.8.12
/// @notice Initializes the Prize Pool and Yield Service with the required contract connections /// @param _controlledTokens Array of addresses for the Ticket and Sponsorship Tokens controlled by the Prize Pool /// @param _maxExitFeeMantissa The maximum exit fee size, relative to the withdrawal amount /// @param _yieldSource Address of the yield source
function initializeYieldSourcePrizePool ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, IYieldSource _yieldSource ) public initializer { require(address(_yieldSource).isContract(), "YieldSourcePrizePool/yield-source-not-contract-address"); PrizePool.initialize( _reserveRegistry, _controlledTokens, _maxExitFeeMantissa ); yieldSource = _yieldSource; // A hack to determine whether it's an actual yield source (bool succeeded,) = address(_yieldSource).staticcall(abi.encode(_yieldSource.depositToken.selector)); require(succeeded, "YieldSourcePrizePool/invalid-yield-source"); emit YieldSourcePrizePoolInitialized(address(_yieldSource)); }
0.6.12
/** * @dev Transfer underlying token interest earned to recipient * @return uint256 Amount dispensed */
function dispenseEarning() public returns (uint256) { if (earningRecipient == address(0)) { return 0; } uint256 earnings = calcUndispensedEarningInUnderlying(); // total dispense amount = earning + withdraw fee uint256 totalDispenseAmount = earnings.add(balanceInUnderlying()); if (totalDispenseAmount < earningDispenseThreshold) { return 0; } // Withdraw earning from provider _withdrawFromProvider(earnings); // Transfer earning + withdraw fee to recipient IERC20(underlyingToken).safeTransfer(earningRecipient, totalDispenseAmount); emit Dispensed(underlyingToken, totalDispenseAmount); return totalDispenseAmount; }
0.5.16
/** * @dev Transfer reward token earned to recipient * @return uint256 Amount dispensed */
function dispenseReward() public returns (uint256) { if (rewardRecipient == address(0)) { return 0; } uint256 rewards = calcUndispensedProviderReward(); if (rewards < rewardDispenseThreshold) { return 0; } // Transfer COMP rewards to recipient IERC20(rewardToken).safeTransfer(rewardRecipient, rewards); emit Dispensed(rewardToken, rewards); return rewards; }
0.5.16
// add new team percentage of tokens
function addTeamAddressInternal(address addr, uint release_time, uint token_percentage) internal { if((team_token_percentage_total.add(token_percentage)) > team_token_percentage_max) revert(); if((team_token_percentage_total.add(token_percentage)) > 100) revert(); if(team_addresses_token_percentage[addr] != 0) revert(); team_addresses_token_percentage[addr]= token_percentage; team_addresses_idx[team_address_count]= addr; team_address_count++; team_token_percentage_total = team_token_percentage_total.add(token_percentage); AddTeamAddress(addr, release_time, token_percentage); }
0.4.19
/* Crowdfund state machine management. */
function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (now < startsAt) return State.PreFunding; else if (now <= endsAt && !isMinimumGoalReached()) return State.Funding; else if (isMinimumGoalReached()) return State.Success; else if (!isMinimumGoalReached() && crowdsale_eth_fund > 0 && loadedRefund >= crowdsale_eth_fund) return State.Refunding; else return State.Failure; }
0.4.19
//generate team tokens in accordance with percentage of total issue tokens, not preallocate
function createTeamTokenByPercentage() onlyOwner internal { //uint total= token.totalSupply(); uint total= tokensSold; //uint tokens= total.mul(100).div(100-team_token_percentage_total).sub(total); uint tokens= total.mul(team_token_percentage_total).div(100-team_token_percentage_total); for(uint i=0; i<team_address_count; i++) { address addr= team_addresses_idx[i]; if(addr==0x0) continue; uint ntoken= tokens.mul(team_addresses_token_percentage[addr]).div(team_token_percentage_total); token.mint(addr, ntoken); createTeamTokenEvent(addr, ntoken); } }
0.4.19
// Update the given pool's PEARL allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); uint256 prevAllocPoint = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; if (prevAllocPoint != _allocPoint) { updateStakingPool(); } }
0.8.11
// Stake PEARL tokens to MasterChef
function enterStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; updatePool(0); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accPearlPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { pearl.transfer(msg.sender, pending); } } if(_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(oyster), _amount); user.amount = user.amount.add(_amount); pearlStaked += _amount; } user.rewardDebt = user.amount.mul(pool.accPearlPerShare).div(1e12); oyster.mint(msg.sender, _amount); emit Deposit(msg.sender, 0, _amount); }
0.8.11
// Withdraw PEARL tokens from STAKING.
function leaveStaking(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[0][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(0); uint256 pending = user.amount.mul(pool.accPearlPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { pearl.transfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pearlStaked -= _amount; safePearlTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accPearlPerShare).div(1e12); oyster.burn(msg.sender, _amount); emit Withdraw(msg.sender, 0, _amount); }
0.8.11
////////////////////////////////////////////////////////////////////////////////////////OCTAPAY MINTING FUNCTION///////////////////////////////////////////////////////////////////////////////////////////
function mintOctapay (uint _mintBatchAmount) external returns (uint) { require(msg.sender == mintOctpayLockingAddr , 'Only the staking pool contract address set by Payzus Admin is allowed to call this mint octapay function' ); require((currentSupply < totalSupply) && (maximumSupplyReached == false) , "Octapay reached its Maximum Supply"); //currentSupply = initialSupply + _mintBatchAmount + currentSupply; currentSupply = (initialSupply).add(_mintBatchAmount).add(currentSupply); balanceOf[mintOctpayLockingAddr] = _mintBatchAmount ; // this should turn to zero once current it distribute all its token if (currentSupply >= totalSupply ) { require(tokenBurningStart == false , 'Token Burning has already been triggered Cant be triggered twice'); tokenBurningStart = true ; maximumSupplyReached = true ; burnOctapayFirstSlot(); } }
0.5.10
//This function is allowed to call by only Payzus Admin Once Octapay Total Supply is reached and first slot of auto token burning has been completed
function burnOctapayForSecondSlot () public onlyPayzusAdmin returns(uint) { require((now > firstSlotTokenBurningTime + 30 days) &&(tokenBurningCounter == 2 ) && (tokenBurningCounter <= totalTokenBurninglot) && (maximumSupplyReached = true) ,'All four slots of token birning acheived' ); if(octapayContractReserveTokenBalance > 0) { // octapayContractReserveTokenBalance = octapayContractReserveTokenBalance - octapayReserveBalFirstBurningSlot ; // totalSupply = totalSupply - (octapayReserveBalFirstBurningSlot *1000000000000000000) ; octapayContractReserveTokenBalance = octapayContractReserveTokenBalance.sub(octapayReserveBalFirstBurningSlot) ; totalSupply = totalSupply.sub(octapayReserveBalFirstBurningSlot *1000000000000000000) ; tokenBurningCounter = tokenBurningCounter+ 1; secondSlotTokenBurningTime = now ; } }
0.5.10
/// @notice Claim accumulated earnings.
function claim(address _to, uint256 _earningsToDate, uint256 _nonce, bytes memory _signature) external { require(_earningsToDate > claimedAmount[_to], "nothing to claim"); require(_nonce > lastUsedNonce[_to], "nonce is too old"); address signer = ECDSA.recover(hashForSignature(_to, _earningsToDate, _nonce), _signature); require(signer == accountManager, "signer is not the account manager"); lastUsedNonce[_to] = _nonce; uint256 claimableAmount = _earningsToDate.sub(claimedAmount[_to]); claimedAmount[_to] = _earningsToDate; kprToken.transfer(_to, claimableAmount); emit Claimed(_to, claimableAmount); }
0.6.9
/** *change dates */
function ChangeDates(uint256 _preSaleStartdate, uint256 _preSaleDeadline, uint256 _mainSaleStartdate, uint256 _mainSaleDeadline) public onlyOwner { if(_preSaleStartdate != 0){ preSaleStartdate = _preSaleStartdate; } if(_preSaleDeadline != 0){ preSaleDeadline = _preSaleDeadline; } if(_mainSaleStartdate != 0){ mainSaleStartdate = _mainSaleStartdate; } if(_mainSaleDeadline != 0){ mainSaleDeadline = _mainSaleDeadline; } if(crowdsaleClosed == true){ crowdsaleClosed = false; } }
0.4.25
/** * @notice View function to check if a timelock for the specified function and * arguments has completed. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. * @return A boolean indicating if the timelock exists or not and the time at * which the timelock completes if it does exist. */
function getTimelock( bytes4 functionSelector, bytes memory arguments ) public view returns ( bool exists, bool completed, bool expired, uint256 completionTime, uint256 expirationTime ) { // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // Get information on the current timelock, if one exists. completionTime = uint256(_timelocks[functionSelector][timelockID].complete); exists = completionTime != 0; expirationTime = uint256(_timelocks[functionSelector][timelockID].expires); completed = exists && now > completionTime; expired = exists && now > expirationTime; }
0.5.11
/** * @notice Internal function for setting a new timelock interval for a given * function selector. The default for this function may also be modified, but * excessive values will cause the `modifyTimelockInterval` function to become * unusable. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */
function _modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) internal { // Ensure that the timelock has been set and is completed. _enforceTimelockPrivate( _MODIFY_TIMELOCK_INTERVAL_SELECTOR, abi.encode(functionSelector, newTimelockInterval) ); // Clear out the existing timelockID protection for the given function. delete _protectedTimelockIDs[ _MODIFY_TIMELOCK_INTERVAL_SELECTOR ][functionSelector]; // Set new timelock interval and emit a `TimelockIntervalModified` event. _setTimelockIntervalPrivate(functionSelector, newTimelockInterval); }
0.5.11
/** * @notice Internal function for setting a new timelock expiration for a given * function selector. Once the minimum interval has elapsed, the timelock will * expire once the specified expiration time has elapsed. Setting this value * too low will result in timelocks that are very difficult to execute * correctly. Be sure to override the public version of this function with * appropriate access controls. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration the new minimum timelock expiration to set for * the given function. */
function _modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) internal { // Ensure that the timelock has been set and is completed. _enforceTimelockPrivate( _MODIFY_TIMELOCK_EXPIRATION_SELECTOR, abi.encode(functionSelector, newTimelockExpiration) ); // Clear out the existing timelockID protection for the given function. delete _protectedTimelockIDs[ _MODIFY_TIMELOCK_EXPIRATION_SELECTOR ][functionSelector]; // Set new default expiration and emit a `TimelockExpirationModified` event. _setTimelockExpirationPrivate(functionSelector, newTimelockExpiration); }
0.5.11
/** * @notice Internal function to set an initial timelock interval for a given * function selector. Only callable during contract creation. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */
function _setInitialTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) internal { // Ensure that this function is only callable during contract construction. assembly { if extcodesize(address) { revert(0, 0) } } // Set the timelock interval and emit a `TimelockIntervalModified` event. _setTimelockIntervalPrivate(functionSelector, newTimelockInterval); }
0.5.11
/** * @notice Private function to ensure that a timelock is complete or expired * and to clear the existing timelock if it is complete so it cannot later be * reused. * @param functionSelector function to be called. * @param arguments The abi-encoded arguments of the function to be called. */
function _enforceTimelockPrivate( bytes4 functionSelector, bytes memory arguments ) private { // Get timelock ID using the supplied function arguments. bytes32 timelockID = keccak256(abi.encodePacked(arguments)); // Get the current timelock, if one exists. Timelock memory timelock = _timelocks[functionSelector][timelockID]; uint256 currentTimelock = uint256(timelock.complete); uint256 expiration = uint256(timelock.expires); // Ensure that the timelock is set and has completed. require( currentTimelock != 0 && currentTimelock <= now, "Timelock is incomplete." ); // Ensure that the timelock has not expired. require(expiration > now, "Timelock has expired."); // Clear out the existing timelock so that it cannot be reused. delete _timelocks[functionSelector][timelockID]; }
0.5.11
/** * @notice Private function for setting a new timelock interval for a given * function selector. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval the new minimum timelock interval to set for the * given function. */
function _setTimelockIntervalPrivate( bytes4 functionSelector, uint256 newTimelockInterval ) private { // Ensure that the new timelock interval will not cause an overflow error. require( newTimelockInterval < _A_TRILLION_YEARS, "Supplied minimum timelock interval is too large." ); // Get the existing timelock interval, if any. uint256 oldTimelockInterval = uint256( _timelockDefaults[functionSelector].interval ); // Update the timelock interval on the provided function. _timelockDefaults[functionSelector].interval = uint128(newTimelockInterval); // Emit a `TimelockIntervalModified` event with the appropriate arguments. emit TimelockIntervalModified( functionSelector, oldTimelockInterval, newTimelockInterval ); }
0.5.11
/** * @notice Initiates a timelocked account recovery process for a smart wallet * user signing key. Only the owner may call this function. Once the timelock * period is complete (and before it has expired) the owner may call `recover` * to complete the process and reset the user's signing key. * @param smartWallet the smart wallet address. * @param userSigningKey the new user signing key. * @param extraTime Additional time in seconds to add to the timelock. */
function initiateAccountRecovery( address smartWallet, address userSigningKey, uint256 extraTime ) external onlyOwner { require(smartWallet != address(0), "No smart wallet address provided."); require(userSigningKey != address(0), "No new user signing key provided."); // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.recover.selector, abi.encode(smartWallet, userSigningKey), extraTime ); }
0.5.11
/** * @notice Initiates a timelocked account recovery disablement process for a * smart wallet. Only the owner may call this function. Once the timelock * period is complete (and before it has expired) the owner may call * `disableAccountRecovery` to complete the process and opt a smart wallet out * of account recovery. Once account recovery has been disabled, it cannot be * reenabled - the process is irreversible. * @param smartWallet the smart wallet address. * @param extraTime Additional time in seconds to add to the timelock. */
function initiateAccountRecoveryDisablement( address smartWallet, uint256 extraTime ) external onlyOwner { require(smartWallet != address(0), "No smart wallet address provided."); // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.disableAccountRecovery.selector, abi.encode(smartWallet), extraTime ); }
0.5.11
/** * @notice Timelocked function to opt a given wallet out of account recovery. * This action cannot be undone - any future account recovery would require an * upgrade to the smart wallet implementation itself and is not likely to be * supported. Only the owner may call this function. * @param smartWallet Address of the smart wallet to disable account recovery * for. */
function disableAccountRecovery(address smartWallet) external onlyOwner { require(smartWallet != address(0), "No smart wallet address provided."); // Ensure that the timelock has been set and is completed. _enforceTimelock(abi.encode(smartWallet)); // Register the specified wallet as having opted out of account recovery. _accountRecoveryDisabled[smartWallet] = true; // Emit an event to signify the wallet in question is no longer recoverable. emit RecoveryDisabled(smartWallet); }
0.5.11
/** * @notice Sets the timelock for a new timelock interval for a given function * selector. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. * @param extraTime Additional time in seconds to add to the timelock. */
function initiateModifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval, uint256 extraTime ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure a timelock interval over eight weeks is not set on this function. if (functionSelector == this.modifyTimelockInterval.selector) { require( newTimelockInterval <= 8 weeks, "Timelock interval of modifyTimelockInterval cannot exceed eight weeks." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockInterval.selector, abi.encode(functionSelector, newTimelockInterval), extraTime ); }
0.5.11
/** * @notice Sets a new timelock interval for a given function selector. The * default for this function may also be modified, but has a maximum allowable * value of eight weeks. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * interval for. * @param newTimelockInterval The new timelock interval to set for the given * function selector. */
function modifyTimelockInterval( bytes4 functionSelector, uint256 newTimelockInterval ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `_modifyTimelockInterval` function. _modifyTimelockInterval(functionSelector, newTimelockInterval); }
0.5.11
/** * @notice Sets a new timelock expiration for a given function selector. The * default Only the owner may call this function. New expiration durations may * not exceed one month. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. * @param extraTime Additional time in seconds to add to the timelock. */
function initiateModifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration, uint256 extraTime ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Ensure that the supplied default expiration does not exceed 1 month. require( newTimelockExpiration <= 30 days, "New timelock expiration cannot exceed one month." ); // Ensure a timelock expiration under one hour is not set on this function. if (functionSelector == this.modifyTimelockExpiration.selector) { require( newTimelockExpiration >= 60 minutes, "Expiration of modifyTimelockExpiration must be at least an hour long." ); } // Set the timelock and emit a `TimelockInitiated` event. _setTimelock( this.modifyTimelockExpiration.selector, abi.encode(functionSelector, newTimelockExpiration), extraTime ); }
0.5.11
/** * @notice Sets a new timelock expiration for a given function selector. The * default for this function may also be modified, but has a minimum allowable * value of one hour. Only the owner may call this function. * @param functionSelector the selector of the function to set the timelock * expiration for. * @param newTimelockExpiration The new timelock expiration to set for the * given function selector. */
function modifyTimelockExpiration( bytes4 functionSelector, uint256 newTimelockExpiration ) external onlyOwner { // Ensure that a function selector is specified (no 0x00000000 selector). require( functionSelector != bytes4(0), "Function selector cannot be empty." ); // Continue via logic in the inherited `_modifyTimelockExpiration` function. _modifyTimelockExpiration( functionSelector, newTimelockExpiration ); }
0.5.11
/// @dev Toggle boolean flag to allow or prevent access /// @param _address Boolean value, true if authorized, false otherwise /// @param _authorization key for specific authorization
function toggleAuthorization(address _address, bytes32 _authorization) public ifAuthorized(msg.sender, PRESIDENT) { /// Prevent inadvertent self locking out, cannot change own authority require(_address != msg.sender, "Cannot change own permissions."); /// No need for lower level authorization to linger if (_authorization == PRESIDENT && !authorized[_address][PRESIDENT]) authorized[_address][STAFF_MEMBER] = false; authorized[_address][_authorization] = !authorized[_address][_authorization]; }
0.4.23
/// @dev Set an address at _key location /// @param _address Address to set /// @param _key bytes32 key location
function setReference(address _address, bytes32 _key) external ifAuthorized(msg.sender, PRESIDENT) { require(_address != address(0), "setReference: Unexpectedly _address is 0x0"); if (_key == bytes32(0)) emit LogicUpgrade(references[bytes32(0)], _address); else emit StorageUpgrade(references[_key], _address); if (references[_key] != address(0)) delete references[_key]; references[_key] = _address; }
0.4.23
// records time at which investments were made // this function called every time anyone sends a transaction to this contract
function () external payable { // if sender (aka YOU) is invested more than 0 ether if (invested[msg.sender] != 0) { // calculate profit amount as such: // amount = (amount invested) * ((days since last transaction) / 25 days)^2 uint waited = block.timestamp - atTime[msg.sender]; uint256 amount = invested[msg.sender] * waited * waited / (25 days) / (25 days); msg.sender.send(amount);// send calculated amount to sender (aka YOU) } // record block number and invested amount (msg.value) of this transaction atTime[msg.sender] = block.timestamp; invested[msg.sender] += msg.value; }
0.4.25
// Post image data to the blockchain and log completion // TODO: If not committed for this week use last weeks tokens and days (if it exists)
function postProof(string proofHash) public { WeekCommittment storage committment = commitments[msg.sender][currentWeek()]; if (committment.daysCompleted > currentDayOfWeek()) { emit Log("You have already uploaded proof for today"); require(false); } if (committment.tokensCommitted == 0) { emit Log("You have not committed to this week yet"); require(false); } if (committment.workoutProofs[currentDayOfWeek()] != 0) { emit Log("Proof has already been stored for this day"); require(false); } if (committment.daysCompleted >= committment.daysCommitted) { // Don't allow us to go over our committed days return; } committment.workoutProofs[currentDayOfWeek()] = storeImageString(proofHash); committment.daysCompleted++; initializeWeekData(currentWeek()); WeekData storage week = dataPerWeek[currentWeek()]; week.totalDaysCompleted++; week.totalTokensCompleted = week.totalTokens * week.totalDaysCompleted / week.totalDaysCommitted; if (committment.daysCompleted >= committment.daysCommitted) { week.totalPeopleCompleted++; } }
0.4.24
// Withdraw tokens to eth
function withdraw(uint tokens) public returns (bool success) { require(balances[msg.sender] >= tokens); uint weiToSend = tokens * weiPerToken; require(address(this).balance >= weiToSend); balances[msg.sender] = balances[msg.sender] - tokens; _totalSupply -= tokens; return msg.sender.send(tokens * weiPerToken); }
0.4.24
// Initialize a week data struct
function initializeWeekData(uint _week) public { if (dataPerWeek[_week].initialized) return; WeekData storage week = dataPerWeek[_week]; week.initialized = true; week.totalTokensCompleted = 0; week.totalPeopleCompleted = 0; week.totalTokens = 0; week.totalPeople = 0; week.totalDaysCommitted = 0; week.totalDaysCompleted = 0; }
0.4.24
/// @dev Constructor /// @param _token token address /// @param _ethMultisigWallet wallet address to transfer invested ETH /// @param _tokenMultisigWallet wallet address to withdraw unused tokens /// @param _startTime ICO start time /// @param _duration ICO duration in seconds /// @param _prolongedDuration Prolonged ICO duration in seconds, 0 if no prolongation is planned /// @param _tokenPrice Token price in wei /// @param _minInvestment Minimal investment amount in wei /// @param _allowedSenders List of addresses allowed to send ETH to this contract, empty if anyone is allowed
function TokenAdrTokenSale(address _token, address _ethMultisigWallet, address _tokenMultisigWallet, uint _startTime, uint _duration, uint _prolongedDuration, uint _tokenPrice, uint _minInvestment, address[] _allowedSenders) public { require(_token != 0); require(_ethMultisigWallet != 0); require(_tokenMultisigWallet != 0); require(_duration > 0); require(_tokenPrice > 0); require(_minInvestment > 0); token = ERC20(_token); ethMultisigWallet = _ethMultisigWallet; tokenMultisigWallet = _tokenMultisigWallet; startTime = _startTime; duration = _duration; prolongedDuration = _prolongedDuration; tokenPrice = _tokenPrice; minInvestment = _minInvestment; allowedSenders = _allowedSenders; tokenValueMultiplier = 10 ** token.decimals(); }
0.4.18
/// @dev Token sale state machine management. /// @return Status current status
function getCurrentStatus() public constant returns (Status) { if (startTime > now) return Status.Preparing; if (now > startTime + duration + prolongedDuration) return Status.Finished; if (now > startTime + duration && !prolongationPermitted) return Status.Finished; if (token.balanceOf(address(this)) <= 0) return Status.TokenShortage; if (now > startTime + duration) return Status.ProlongedSelling; if (now >= startTime) return Status.Selling; return Status.Unknown; }
0.4.18
/** * @dev Internal transfer for all functions that transfer. * @param _from The address that is transferring coins. * @param _to The receiving address of the coins. * @param _amount The amount of coins being transferred. **/
function _transfer(address _from, address _to, uint256 _amount) internal returns (bool success) { require (_to != address(0)); require(balances[_from] >= _amount); balances[_from] = balances[_from].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(_from, _to, _amount); return true; }
0.4.25