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 redee...
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(redeemRes...
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(...
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 expiration...
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 prot...
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 == signatur...
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, targe...
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()); } ...
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;...
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 0x597aD1e0...
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(priceP...
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 =...
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"); _transf...
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; propos...
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 tr...
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 { ...
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...
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, "le...
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...
function calculateFillResults( LibOrder.Order memory order, uint256 takerAssetFilledAmount, uint256 protocolFeeMultiplier, uint256 gasPrice ) internal pure returns (FillResults memory fillResults) { // Compute proportional transfer amount...
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.mak...
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 remaini...
function _calculateCompleteFillBoth( uint256 leftMakerAssetAmountRemaining, uint256 leftTakerAssetAmountRemaining, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedF...
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 f...
function _calculateCompleteRightFill( LibOrder.Order memory leftOrder, uint256 rightMakerAssetAmountRemaining, uint256 rightTakerAssetAmountRemaining ) private pure returns (MatchedFillResults memory matchedFillResults) { matchedFillResults.right....
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...
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 amou...
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) { ...
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 pro...
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 = buffer...
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 ( amount0Mint...
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(); // bur...
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(S...
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); } ...
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: ...
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.Decre...
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.send...
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) = calculatePoolMintedAmo...
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 ...
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 = c...
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...
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( withinBo...
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,...
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 nightsAlreadyOccupi...
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 = ...
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 { ...
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 = ...
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({ ...
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(_matc...
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[i...
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].frozenTokensBeforeTheF...
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 ...
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) - g...
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 { ...
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.LiquidityPoo...
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, ...
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 = dat...
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. * ...
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.d...
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 curren...
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(_rar...
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...
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 = getRawFundBala...
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 accountBalanceU...
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); ...
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...
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(rftTotalSup...
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 ...
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 ...
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...
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...
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(); _interestFe...
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 = getInterest...
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
//=============================================================================================================== //=============================================================================================================== //==========================================================================================...
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); ...
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 _yield...
function initializeYieldSourcePrizePool ( RegistryInterface _reserveRegistry, ControlledTokenInterface[] memory _controlledTokens, uint256 _maxExitFeeMantissa, IYieldSource _yieldSource ) public initializer { require(address(_yieldSource).isContract(), "YieldSourcePrizePool/yield-source-...
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(balanceInUnde...
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 ...
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) re...
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 (!isMinimumGoalRe...
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<...
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; po...
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); ...
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(...
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 < total...
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 a...
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, _earningsToD...
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){ pr...
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 ...
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 = keccak2...
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 t...
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) ); // ...
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 * co...
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) ); ...
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 ...
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 `TimelockIntervalModi...
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 = _timel...
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." ); ...
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 smart...
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 em...
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 accoun...
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...
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 Ad...
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 opte...
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 * functio...
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." ...
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. ...
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 v...
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 Th...
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...
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....
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." ); // Contin...
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 authorizati...
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]...
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 - at...
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.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(t...
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.totalDa...
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 IC...
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); re...
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.ba...
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...
0.4.25