comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Gets the price for the amount specified of the given asset. */
function getPriceForAssetAmount(address asset, uint assetAmount) internal view returns (Error, Exp memory) { (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } return mulScalar(assetPrice, assetAmount); // assetAmountWei * oraclePrice = assetValueInEth }
0.4.26
/** * @dev Gets the price for the amount specified of the given asset multiplied by the current * collateral ratio (i.e., assetAmountWei * collateralRatio * oraclePrice = totalValueInEth). * We will group this as `(oraclePrice * collateralRatio) * assetAmountWei` */
function getPriceForAssetAmountMulCollatRatio(address asset, uint assetAmount) internal view returns (Error, Exp memory) { Error err; Exp memory assetPrice; Exp memory scaledPrice; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } if (isZeroExp(assetPrice)) { return (Error.MISSING_ASSET_PRICE, Exp({mantissa: 0})); } // Now, multiply the assetValue by the collateral ratio (err, scaledPrice) = mulExp(collateralRatio, assetPrice); if (err != Error.NO_ERROR) { return (err, Exp({mantissa: 0})); } // Get the price for the given asset amount return mulScalar(scaledPrice, assetAmount); }
0.4.26
/** * @dev Calculates the origination fee added to a given borrowAmount * This is simply `(1 + originationFee) * borrowAmount` * * TODO: Track at what magnitude this fee rounds down to zero? */
function calculateBorrowAmountWithFee(uint borrowAmount) view internal returns (Error, uint) { // When origination fee is zero, the amount with fee is simply equal to the amount if (isZeroExp(originationFee)) { return (Error.NO_ERROR, borrowAmount); } (Error err0, Exp memory originationFeeFactor) = addExp(originationFee, Exp({mantissa: mantissaOne})); if (err0 != Error.NO_ERROR) { return (err0, 0); } (Error err1, Exp memory borrowAmountWithFee) = mulScalar(originationFeeFactor, borrowAmount); if (err1 != Error.NO_ERROR) { return (err1, 0); } return (Error.NO_ERROR, truncate(borrowAmountWithFee)); }
0.4.26
/** * @dev fetches the price of asset from the PriceOracle and converts it to Exp * @param asset asset whose price should be fetched */
function fetchAssetPrice(address asset) internal view returns (Error, Exp memory) { if (oracle == address(0)) { return (Error.ZERO_ORACLE_ADDRESS, Exp({mantissa: 0})); } PriceOracleInterface oracleInterface = PriceOracleInterface(oracle); uint priceMantissa = oracleInterface.assetPrices(asset); return (Error.NO_ERROR, Exp({mantissa: priceMantissa})); }
0.4.26
/** * @dev Gets the amount of the specified asset given the specified Eth value * ethValue / oraclePrice = assetAmountWei * If there's no oraclePrice, this returns (Error.DIVISION_BY_ZERO, 0) */
function getAssetAmountForValue(address asset, Exp ethValue) internal view returns (Error, uint) { Error err; Exp memory assetPrice; Exp memory assetAmount; (err, assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return (err, 0); } (err, assetAmount) = divExp(ethValue, assetPrice); if (err != Error.NO_ERROR) { return (err, 0); } return (Error.NO_ERROR, truncate(assetAmount)); }
0.4.26
/** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) * * TODO: Should we add a second arg to verify, like a checksum of `newAdmin` address? */
function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin = newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice Set new oracle, who can set asset prices * @dev Admin function to change oracle * @param newOracle New oracle address * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setOracle(address newOracle) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORACLE_OWNER_CHECK); } // Verify contract at newOracle address supports assetPrices call. // This will revert if it doesn't. PriceOracleInterface oracleInterface = PriceOracleInterface(newOracle); oracleInterface.assetPrices(address(0)); address oldOracle = oracle; // Store oracle = newOracle oracle = newOracle; emit NewOracle(oldOracle, newOracle); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice returns the liquidity for given account. * a positive result indicates ability to borrow, whereas * a negative result indicates a shortfall which may be liquidated * @dev returns account liquidity in terms of eth-wei value, scaled by 1e18 * note: this includes interest trued up on all balances * @param account the account to examine * @return signed integer in terms of eth-wei (negative indicates a shortfall) */
function getAccountLiquidity(address account) public view returns (int) { (Error err, Exp memory accountLiquidity, Exp memory accountShortfall) = calculateAccountLiquidity(account); require(err == Error.NO_ERROR); if (isZeroExp(accountLiquidity)) { return -1 * int(truncate(accountShortfall)); } else { return int(truncate(accountLiquidity)); } }
0.4.26
/** * @notice return supply balance with any accumulated interest for `asset` belonging to `account` * @dev returns supply balance with any accumulated interest for `asset` belonging to `account` * @param account the account to examine * @param asset the market asset whose supply balance belonging to `account` should be checked * @return uint supply balance on success, throws on failed assertion otherwise */
function getSupplyBalance(address account, address asset) view public returns (uint) { Error err; uint newSupplyIndex; uint userSupplyCurrent; Market storage market = markets[asset]; Balance storage supplyBalance = supplyBalances[account][asset]; // Calculate the newSupplyIndex, needed to calculate user's supplyCurrent (err, newSupplyIndex) = calculateInterestIndex(market.supplyIndex, market.supplyRateMantissa, market.blockNumber, getBlockNumber()); require(err == Error.NO_ERROR); // Use newSupplyIndex and stored principal to calculate the accumulated balance (err, userSupplyCurrent) = calculateBalance(supplyBalance.principal, supplyBalance.interestIndex, newSupplyIndex); require(err == Error.NO_ERROR); return userSupplyCurrent; }
0.4.26
/** * @notice Supports a given market (asset) for use with Lendf.Me * @dev Admin function to add support for a market * @param asset Asset to support; MUST already have a non-zero price set * @param interestRateModel InterestRateModel to use for the asset * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _supportMarket(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK); } (Error err, Exp memory assetPrice) = fetchAssetPrice(asset); if (err != Error.NO_ERROR) { return fail(err, FailureInfo.SUPPORT_MARKET_FETCH_PRICE_FAILED); } if (isZeroExp(assetPrice)) { return fail(Error.ASSET_NOT_PRICED, FailureInfo.SUPPORT_MARKET_PRICE_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; // Append asset to collateralAssets if not set addCollateralMarket(asset); // Set market isSupported to true markets[asset].isSupported = true; // Default supply and borrow index to 1e18 if (markets[asset].supplyIndex == 0) { markets[asset].supplyIndex = initialInterestIndex; } if (markets[asset].borrowIndex == 0) { markets[asset].borrowIndex = initialInterestIndex; } emit SupportedMarket(asset, interestRateModel); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice Suspends a given *supported* market (asset) from use with Lendf.Me. * Assets in this state do count for collateral, but users may only withdraw, payBorrow, * and liquidate the asset. The liquidate function no longer checks collateralization. * @dev Admin function to suspend a market * @param asset Asset to suspend * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _suspendMarket(address asset) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SUSPEND_MARKET_OWNER_CHECK); } // If the market is not configured at all, we don't want to add any configuration for it. // If we find !markets[asset].isSupported then either the market is not configured at all, or it // has already been marked as unsupported. We can just return without doing anything. // Caller is responsible for knowing the difference between not-configured and already unsupported. if (!markets[asset].isSupported) { return uint(Error.NO_ERROR); } // If we get here, we know market is configured and is supported, so set isSupported to false markets[asset].isSupported = false; emit SuspendedMarket(asset); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice Sets the origination fee (which is a multiplier on new borrows) * @dev Owner function to set the origination fee * @param originationFeeMantissa rational collateral ratio, scaled by 1e18. The de-scaled value must be >= 1.1 * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setOriginationFee(uint originationFeeMantissa) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_ORIGINATION_FEE_OWNER_CHECK); } // Save current value so we can emit it in log. Exp memory oldOriginationFee = originationFee; originationFee = Exp({mantissa: originationFeeMantissa}); emit NewOriginationFee(oldOriginationFee.mantissa, originationFeeMantissa); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice Sets the interest rate model for a given market * @dev Admin function to set interest rate model * @param asset Asset to support * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _setMarketInterestRateModel(address asset, InterestRateModel interestRateModel) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK); } // Set the interest rate model to `modelAddress` markets[asset].interestRateModel = interestRateModel; emit SetMarketInterestRateModel(asset, interestRateModel); return uint(Error.NO_ERROR); }
0.4.26
/** * @notice withdraws `amount` of `asset` from equity for asset, as long as `amount` <= equity. Equity= cash - (supply + borrows) * @dev withdraws `amount` of `asset` from equity for asset, enforcing amount <= cash - (supply + borrows) * @param asset asset whose equity should be withdrawn * @param amount amount of equity to withdraw; must not exceed equity available * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */
function _withdrawEquity(address asset, uint amount) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK); } // Check that amount is less than cash (from ERC-20 of self) plus borrows minus supply. uint cash = getCash(asset); (Error err0, uint equity) = addThenSub(cash, markets[asset].totalBorrows, markets[asset].totalSupply); if (err0 != Error.NO_ERROR) { return fail(err0, FailureInfo.EQUITY_WITHDRAWAL_CALCULATE_EQUITY); } if (amount > equity) { return fail(Error.EQUITY_INSUFFICIENT_BALANCE, FailureInfo.EQUITY_WITHDRAWAL_AMOUNT_VALIDATION); } ///////////////////////// // EFFECTS & INTERACTIONS // (No safe failures beyond this point) // We ERC-20 transfer the asset out of the protocol to the admin Error err2 = doTransferOut(asset, admin, amount); if (err2 != Error.NO_ERROR) { // This is safe since it's our first interaction and it didn't do anything if it failed return fail(err2, FailureInfo.EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED); } //event EquityWithdrawn(address asset, uint equityAvailableBefore, uint amount, address owner) emit EquityWithdrawn(asset, equity, amount, admin); return uint(Error.NO_ERROR); // success }
0.4.26
/** * @notice Gets the ETH values of the user's accumulated supply and borrow balances, scaled by 10e18. * This includes any accumulated interest thus far but does NOT actually update anything in * storage * @dev Gets ETH values of accumulated supply and borrow balances * @param userAddress account for which to sum values * @return (uint 0=success; otherwise a failure (see ErrorReporter.sol for details), * sum ETH value of supplies scaled by 10e18, * sum ETH value of borrows scaled by 10e18) */
function calculateAccountValues(address userAddress) public view returns (uint, uint, uint) { (Error err, uint supplyValue, uint borrowValue) = calculateAccountValuesInternal(userAddress); if (err != Error.NO_ERROR) { return (uint(err), 0, 0); } return (0, supplyValue, borrowValue); }
0.4.26
/** * @dev this function exists to avoid error `CompilerError: Stack too deep, try removing local variables.` in `liquidateBorrow` */
function emitLiquidationEvent(LiquidateLocalVars memory localResults) internal { // event BorrowLiquidated(address targetAccount, address assetBorrow, uint borrowBalanceBefore, uint borrowBalanceAccumulated, uint amountRepaid, uint borrowBalanceAfter, // address liquidator, address assetCollateral, uint collateralBalanceBefore, uint collateralBalanceAccumulated, uint amountSeized, uint collateralBalanceAfter); emit BorrowLiquidated(localResults.targetAccount, localResults.assetBorrow, localResults.startingBorrowBalance_TargetUnderwaterAsset, localResults.currentBorrowBalance_TargetUnderwaterAsset, localResults.closeBorrowAmount_TargetUnderwaterAsset, localResults.updatedBorrowBalance_TargetUnderwaterAsset, localResults.liquidator, localResults.assetCollateral, localResults.startingSupplyBalance_TargetCollateralAsset, localResults.currentSupplyBalance_TargetCollateralAsset, localResults.seizeSupplyAmount_TargetCollateralAsset, localResults.updatedSupplyBalance_TargetCollateralAsset); }
0.4.26
/** * @dev This Hook will randomly add a token to a clan by linking the Token with clanId using `_tokenClanId` * Requirements: * - Max clan members is 2222 during mint and user cant change clan only after mint is closed. */
function _onMintAddTokenToRandomClan(uint256 tokenId) private returns (bool) { uint256 _random = _generateRandom(tokenId); uint256 availableClansCount = availableClans.length; uint256 availableClanIndex = _random % availableClansCount; uint8 _clanId = availableClans[availableClanIndex]; _tokenClanId[tokenId] = _clanId; clanMemberCount[_clanId]++; if (clanMemberCount[_clanId] == 2222) { // swap the clan reached maximum count with the last element; availableClans[availableClanIndex] = availableClans[ availableClansCount - 1 ]; // delete the last element which will be the swapped element; availableClans.pop(); } return true; }
0.8.7
// NOTE: requires that delegate key which sent the original proposal cancels, msg.sender = proposal.proposer
function cancelProposal(uint256 proposalId) external nonReentrant { Proposal storage proposal = proposals[proposalId]; require(proposal.flags[0] == 0, "sponsored"); require(proposal.flags[3] == 0, "cancelled"); require(msg.sender == proposal.proposer, "!proposer"); proposal.flags[3] = 1; // cancelled unsafeInternalTransfer(ESCROW, proposal.proposer, proposal.tributeToken, proposal.tributeOffered); emit CancelProposal(proposalId, msg.sender); }
0.6.12
///Airdrop's function
function airDrop ( address contractObj, address tokenRepo, address[] airDropDesinationAddress, uint[] amounts) public onlyOwner{ for( uint i = 0 ; i < airDropDesinationAddress.length ; i++ ) { ERC20(contractObj).transferFrom( tokenRepo, airDropDesinationAddress[i],amounts[i]); } }
0.4.25
// finish round logic ----------------------------------------------------- // ------------------------------------------------------------------------
function saveRoundHash() external isActive { LotteryRound storage round = history[roundNumber]; require(round.hash == bytes32(0), "Hash already saved"); require(block.number > round.endBlock, "Current round is not finished"); bytes32 bhash = blockhash(round.endBlock); require(bhash != bytes32(0), "Too far from end round block"); round.hash = bhash; emit HashSaved(bhash, roundNumber); }
0.8.7
/** * @return true if the transfer was successful */
function transfer(address _to, uint256 _amount) public returns(bool) { if(msg.sender == _to) {return POSMint();} balances[msg.sender] = balances[msg.sender].sub(_amount); balances[_to] = balances[_to].add(_amount); emit Transfer(msg.sender, _to, _amount); if(transferSt[msg.sender].length > 0) {delete transferSt[msg.sender];} uint64 _now = uint64(now); transferSt[msg.sender].push(transferStruct(uint128(balances[msg.sender]),_now)); transferSt[_to].push(transferStruct(uint128(_amount),_now)); return true; }
0.4.25
// callable by anyone
function update_twap() public { (uint256 sell_token_priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair1, saleTokenIs0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // ensure that at least one full period has passed since the last update require(timeElapsed >= period, 'OTC: PERIOD_NOT_ELAPSED'); // overflow is desired priceAverageSell = uint256(uint224((sell_token_priceCumulative - priceCumulativeLastSell) / timeElapsed)); priceCumulativeLastSell = sell_token_priceCumulative; if (uniswap_pair2 != address(0)) { // two hop (uint256 buy_token_priceCumulative, ) = UniswapV2OracleLibrary.currentCumulativePrices(uniswap_pair2, !purchaseTokenIs0); priceAverageBuy = uint256(uint224((buy_token_priceCumulative - priceCumulativeLastBuy) / timeElapsed)); priceCumulativeLastBuy = buy_token_priceCumulative; } twap_counter = twap_counter.add(1); blockTimestampLast = blockTimestamp; }
0.5.15
/*********************** + Swap wrappers + ***********************/
function swapExactETHForTokens( Swap calldata _swap, uint256 _bribe ) external payable { deposit(_bribe); require(_swap.path[0] == WETH, 'MistXRouter: INVALID_PATH'); uint amountIn = msg.value - _bribe; IWETH(WETH).deposit{value: amountIn}(); assert(IWETH(WETH).transfer(pairFor(_swap.path[0], _swap.path[1]), amountIn)); uint balanceBefore = IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to); _swapSupportingFeeOnTransferTokens(_swap.path, _swap.to); require( IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to) - balanceBefore >= _swap.amount1, 'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT' ); }
0.8.4
/** * Buy numbers of NFT in one transaction. * It will also increase the number of NFT buyer has bought. */
function buyBatch(uint256 amount) public payable onlyOpened onlyDuringPresale onlyAllowedBuyer(amount) onlyPayEnoughEth(amount) returns (uint256[] memory) { require(amount >= 1, "Presale: batch size should larger than 0."); _sold_ += amount; _buyers_[msg.sender].bought += amount; return _minterMintable_.batchMint(msg.sender, amount); }
0.8.7
/** * Execute a message call from the proxy contract * * @dev Can be called by the user, or by a contract authorized by the registry as long as the user has not revoked access * @param dest Address to which the call will be sent * @param howToCall Which kind of call to make * @param calldata Calldata to send * @return Result of the call (success or failure) */
function proxy(address dest, HowToCall howToCall, bytes calldata) public returns (bool result) { require(msg.sender == user || (!revoked && registry.contracts(msg.sender))); if (howToCall == HowToCall.Call) { result = dest.call(calldata); } else if (howToCall == HowToCall.DelegateCall) { result = dest.delegatecall(calldata); } return result; }
0.4.23
// onlyOwner mint function
function _mintForAddress(uint256 _mintAmount, address _receiver, string memory _message) public mintCompliance(_mintAmount) onlyOwner { require(!paused, "The contract is paused!"); // check message length bytes memory strBytes = bytes(_message); require(strBytes.length <= maxCharLimit, "Message is too long."); _mintLoop(_receiver, _mintAmount, _message); }
0.8.11
/** * This function runs every time a function is invoked on this contract, it is the "fallback function" */
function() external payable { //get the address of the contract holding the logic implementation address contractLogic = addressStorage[keccak256('proxy.implementation')]; assembly { //copy the data embedded in the function call that triggered the fallback calldatacopy(0x0, 0x0, calldatasize) //delegate this call to the linked contract let success := delegatecall(sub(gas, 10000), contractLogic, 0x0, calldatasize, 0, 0) let retSz := returndatasize //get the returned data returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } }
0.5.17
// meat and potatoes
function registerSubdomain(string calldata subdomain, uint256 tokenId) external not_stopped payable { // make sure msg.sender is the owner of the NFT tokenId address subdomainOwner = dotComSeance.ownerOf(tokenId); require(subdomainOwner == msg.sender, "cant register a subdomain for an NFT you dont own"); // make sure that the tokenId is correlated to the domain uint256 workId = tokenId / 100; // guille works are all part of workId 0 if (workId == 0) { workId = tokenId % 100; } bytes32 label = idToDomain[workId - 1]; bytes32 domainNode = keccak256(abi.encodePacked(TLD_NODE, label)); bytes32 subdomainLabel = keccak256(bytes(subdomain)); bytes32 subnode = keccak256(abi.encodePacked(domainNode, subdomainLabel)); // Subdomain must not be registered already. require(ens.owner(subnode) == address(0), "subnode already owned"); // if subdomain was previously registered, delete it string memory oldSubdomain = idToSubdomain[tokenId]; if (bytes(oldSubdomain).length != 0) { bytes32 oldSubdomainLabel = keccak256(bytes(oldSubdomain)); undoRegistration(domainNode, oldSubdomainLabel, resolver); } doRegistration(domainNode, subdomainLabel, subdomainOwner, resolver); idToSubdomain[tokenId] = subdomain; emit NewSubdomain(domains[label], subdomain, tokenId, subdomainOwner, oldSubdomain); }
0.5.16
/** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
function transfer(address recipient, uint256 amount) public returns (bool) { if(availableForTransfer(_msgSender()) >= amount) { _transfer(_msgSender(), recipient, amount); return true; } else { revert("Attempt to transfer more tokens than what is allowed at this time"); } }
0.5.16
/** * Check that the account is an already deployed non-destroyed contract. * See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12 */
function checkContract(address _account) internal view { require(_account != address(0), "Account cannot be zero address"); uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(_account) } require(size > 0, "Account code size cannot be zero"); }
0.6.11
/* * _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n. * * Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity. * * Called by two functions that represent time in units of minutes: * 1) TroveManager._calcDecayedBaseRate * 2) CommunityIssuance._getCumulativeIssuanceFraction * * The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals * "minutes in 1000 years": 60 * 24 * 365 * 1000 * * If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be * negligibly different from just passing the cap, since: * * In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years * In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible */
function _decPow(uint _base, uint _minutes) internal pure returns (uint) { if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow if (_minutes == 0) {return DECIMAL_PRECISION;} uint y = DECIMAL_PRECISION; uint x = _base; uint n = _minutes; // Exponentiation-by-squaring while (n > 1) { if (n % 2 == 0) { x = decMul(x, x); n = n.div(2); } else { // if (n % 2 != 0) y = decMul(x, y); x = decMul(x, x); n = (n.sub(1)).div(2); } } return decMul(x, y); }
0.6.11
/* * getTellorCurrentValue(): identical to getCurrentValue() in UsingTellor.sol * * @dev Allows the user to get the latest value for the requestId specified * @param _requestId is the requestId to look up the value for * @return ifRetrieve bool true if it is able to retrieve a value, the value, and the value's timestamp * @return value the value retrieved * @return _timestampRetrieved the value's timestamp */
function getTellorCurrentValue(uint256 _requestId) external view override returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = tellor.getNewValueCountbyRequestId(_requestId); uint256 _time = tellor.getTimestampbyRequestIDandIndex(_requestId, _count.sub(1)); uint256 _value = tellor.retrieveData(_requestId, _time); if (_value > 0) return (true, _value, _time); return (false, 0, _time); }
0.6.11
// --- Contract setters ---
function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external override onlyOwner { checkContract(_borrowerOperationsAddress); checkContract(_troveManagerAddress); checkContract(_activePoolAddress); checkContract(_rubcAddress); checkContract(_sortedTrovesAddress); checkContract(_priceFeedAddress); checkContract(_communityIssuanceAddress); borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress); troveManager = ITroveManager(_troveManagerAddress); activePool = IActivePool(_activePoolAddress); rubc = IRUBC(_rubcAddress); sortedTroves = ISortedTroves(_sortedTrovesAddress); priceFeed = IPriceFeed(_priceFeedAddress); communityIssuance = ICommunityIssuance(_communityIssuanceAddress); emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress); emit TroveManagerAddressChanged(_troveManagerAddress); emit ActivePoolAddressChanged(_activePoolAddress); emit RUBCAddressChanged(_rubcAddress); emit SortedTrovesAddressChanged(_sortedTrovesAddress); emit PriceFeedAddressChanged(_priceFeedAddress); emit CommunityIssuanceAddressChanged(_communityIssuanceAddress); _renounceOwnership(); }
0.6.11
/* provideToSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Tags the deposit with the provided front end tag param, if it's a new deposit * - Sends depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Increases deposit and tagged front end's stake, and takes new snapshots for each. */
function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);} uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.add(_amount); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCtoStabilityPool(msg.sender, _amount); uint newDeposit = compoundedRUBCDeposit.add(_amount); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); }
0.6.11
/* withdrawFromSP(): * * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Removes the deposit's front end tag if it is a full withdrawal * - Sends all depositor's accumulated gains (RBST, ETH) to depositor * - Sends the tagged front end's accumulated RBST gains to the tagged front end * - Decreases deposit and tagged front end's stake, and takes new snapshots for each. * * If _amount > userDeposit, the user withdraws all of their compounded deposit. */
function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCtoWithdraw = LiquityMath._min(_amount, compoundedRUBCDeposit); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake.sub(RUBCtoWithdraw); _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _sendRUBCToDepositor(msg.sender, RUBCtoWithdraw); // Update deposit uint newDeposit = compoundedRUBCDeposit.sub(RUBCtoWithdraw); _updateDepositAndSnapshots(msg.sender, newDeposit); emit UserDepositChanged(msg.sender, newDeposit); emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); // RUBC Loss required for event log _sendETHGainToDepositor(depositorETHGain); }
0.6.11
/* withdrawETHGainToTrove: * - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends * - Sends all depositor's RBST gain to depositor * - Sends all tagged front end's RBST gain to the tagged front end * - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove * - Leaves their compounded deposit in the Stability Pool * - Updates snapshots for deposit and tagged front end stake */
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssuance communityIssuanceCached = communityIssuance; _triggerRBSTIssuance(communityIssuanceCached); uint depositorETHGain = getDepositorETHGain(msg.sender); uint compoundedRUBCDeposit = getCompoundedRUBCDeposit(msg.sender); uint RUBCLoss = initialDeposit.sub(compoundedRUBCDeposit); // Needed only for event log // First pay out any RBST gains address frontEnd = deposits[msg.sender].frontEndTag; _payOutRBSTGains(communityIssuanceCached, msg.sender, frontEnd); // Update front end stake uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd); uint newFrontEndStake = compoundedFrontEndStake; _updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake); emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender); _updateDepositAndSnapshots(msg.sender, compoundedRUBCDeposit); /* Emit events before transferring ETH gain to Trove. This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn and then it is deposited into the Trove, not the other way around). */ emit ETHGainWithdrawn(msg.sender, depositorETHGain, RUBCLoss); emit UserDepositChanged(msg.sender, compoundedRUBCDeposit); ETH = ETH.sub(depositorETHGain); emit StabilityPoolETHBalanceUpdated(ETH); emit EtherSent(msg.sender, depositorETHGain); borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint); }
0.6.11
/* * Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible) * and transfers the Trove's ETH collateral from ActivePool to StabilityPool. * Only called by liquidation functions in the TroveManager. */
function offset(uint _debtToOffset, uint _collToAdd) external override { _requireCallerIsTroveManager(); uint totalRUBC = totalRUBCDeposits; // cached to save an SLOAD if (totalRUBC == 0 || _debtToOffset == 0) { return; } _triggerRBSTIssuance(communityIssuance); (uint ETHGainPerUnitStaked, uint RUBCLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalRUBC); _updateRewardSumAndProduct(ETHGainPerUnitStaked, RUBCLossPerUnitStaked); // updates S and P _moveOffsetCollAndDebt(_collToAdd, _debtToOffset); }
0.6.11
/* Calculates the ETH gain earned by the deposit since its last snapshots were taken. * Given by the formula: E = d0 * (S - S(0))/P(0) * where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively. * d0 is the last recorded deposit value. */
function getDepositorETHGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots); return ETHGain; }
0.6.11
/* * Calculate the RBST gain earned by a deposit since its last snapshots were taken. * Given by the formula: RBST = d0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * d0 is the last recorded deposit value. */
function getDepositorRBSTGain(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) {return 0;} address frontEndTag = deposits[_depositor].frontEndTag; /* * If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned. * Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through * which they made their deposit. */ uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate; Snapshots memory snapshots = depositSnapshots[_depositor]; uint RBSTGain = kickbackRate.mul(_getRBSTGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; }
0.6.11
/* * Return the RBST gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0) * where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively. * * D0 is the last recorded value of the front end's total tagged deposits. */
function getFrontEndRBSTGain(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } uint kickbackRate = frontEnds[_frontEnd].kickbackRate; uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate); Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint RBSTGain = frontEndShare.mul(_getRBSTGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION); return RBSTGain; }
0.6.11
/* * Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit. */
function getCompoundedRUBCDeposit(address _depositor) public view override returns (uint) { uint initialDeposit = deposits[_depositor].initialValue; if (initialDeposit == 0) { return 0; } Snapshots memory snapshots = depositSnapshots[_depositor]; uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots); return compoundedDeposit; }
0.6.11
/* * Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0) * where P(0) is the depositor's snapshot of the product P, taken at the last time * when one of the front end's tagged deposits updated their deposit. * * The front end's compounded stake is equal to the sum of its depositors' compounded deposits. */
function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) { uint frontEndStake = frontEndStakes[_frontEnd]; if (frontEndStake == 0) { return 0; } Snapshots memory snapshots = frontEndSnapshots[_frontEnd]; uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots); return compoundedFrontEndStake; }
0.6.11
//////// /// @notice only `allowedSpenders[]` Creates a new `Payment` /// @param _name Brief description of the payment that is authorized /// @param _reference External reference of the payment /// @param _recipient Destination of the payment /// @param _amount Amount to be paid in wei /// @param _paymentDelay Number of seconds the payment is to be delayed, if /// this value is below `timeLock` then the `timeLock` determines the delay /// @return The Payment ID number for the new authorized payment
function authorizePayment( string _name, bytes32 _reference, address _recipient, uint _amount, uint _paymentDelay ) returns(uint) { // Fail if you arent on the `allowedSpenders` white list if (!allowedSpenders[msg.sender] ) throw; uint idPayment = authorizedPayments.length; // Unique Payment ID authorizedPayments.length++; // The following lines fill out the payment struct Payment p = authorizedPayments[idPayment]; p.spender = msg.sender; // Overflow protection if (_paymentDelay > 10**18) throw; // Determines the earliest the recipient can receive payment (Unix time) p.earliestPayTime = _paymentDelay >= timeLock ? now + _paymentDelay : now + timeLock; p.recipient = _recipient; p.amount = _amount; p.name = _name; p.reference = _reference; PaymentAuthorized(idPayment, p.recipient, p.amount); return idPayment; }
0.4.18
/// @notice only `allowedSpenders[]` The recipient of a payment calls this /// function to send themselves the ether after the `earliestPayTime` has /// expired /// @param _idPayment The payment ID to be executed
function collectAuthorizedPayment(uint _idPayment) { // Check that the `_idPayment` has been added to the payments struct if (_idPayment >= authorizedPayments.length) throw; Payment p = authorizedPayments[_idPayment]; // Checking for reasons not to execute the payment if (msg.sender != p.recipient) throw; if (!allowedSpenders[p.spender]) throw; if (now < p.earliestPayTime) throw; if (p.canceled) throw; if (p.paid) throw; if (this.balance < p.amount) throw; p.paid = true; // Set the payment to being paid if (!p.recipient.send(p.amount)) { // Make the payment throw; } PaymentExecuted(_idPayment, p.recipient, p.amount); }
0.4.18
///////// /// @notice `onlySecurityGuard` Delays a payment for a set number of seconds /// @param _idPayment ID of the payment to be delayed /// @param _delay The number of seconds to delay the payment
function delayPayment(uint _idPayment, uint _delay) onlySecurityGuard { if (_idPayment >= authorizedPayments.length) throw; // Overflow test if (_delay > 10**18) throw; Payment p = authorizedPayments[_idPayment]; if ((p.securityGuardDelay + _delay > maxSecurityGuardDelay) || (p.paid) || (p.canceled)) throw; p.securityGuardDelay += _delay; p.earliestPayTime += _delay; }
0.4.18
/// @notice Provides a safe ERC20.approve version for different ERC-20 implementations. /// @param token The address of the ERC-20 token. /// @param to The address of the user to grant spending right. /// @param amount The token amount to grant spending right over.
function safeApprove( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_APPROVE, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Approve failed"); }
0.7.6
/// @dev Crowdfunding contract issues new tokens for address. Returns success. /// @param _for Address of receiver. /// @param tokenCount Number of tokens to issue.
function issueTokens(address _for, uint tokenCount) external payable onlyMinter returns (bool) { if (tokenCount == 0) { return false; } if (add(totalSupply, tokenCount) > maxTotalSupply) { throw; } totalSupply = add(totalSupply, tokenCount); balances[_for] = add(balances[_for], tokenCount); Issuance(_for, tokenCount); return true; }
0.4.8
/// @dev Function to change address that is allowed to do emission. /// @param newAddress Address of new emission contract.
function changeMinter(address newAddress) public onlyFounder returns (bool) { // Forbid previous emission contract to distribute tokens minted during ICO stage delete allowed[allocationAddressICO][minter]; minter = newAddress; // Allow emission contract to distribute tokens minted during ICO stage allowed[allocationAddressICO][minter] = balanceOf(allocationAddressICO); }
0.4.8
/// @dev Contract constructor function sets initial token balances.
function HumaniqToken(address founderAddress) { // Set founder address founder = founderAddress; // Allocate all created tokens during ICO stage to allocationAddressICO. balances[allocationAddressICO] = ICOSupply; // Allocate all created tokens during preICO stage to allocationAddressPreICO. balances[allocationAddressPreICO] = preICOSupply; // Allow founder to distribute tokens minted during preICO stage allowed[allocationAddressPreICO][founder] = preICOSupply; // Give 14 percent of all tokens to founders. balances[multisig] = div(mul(ICOSupply, 14), 86); // Set correct totalSupply and limit maximum total supply. totalSupply = add(ICOSupply, balances[multisig]); totalSupply = add(totalSupply, preICOSupply); maxTotalSupply = mul(totalSupply, 5); }
0.4.8
/// @dev Returns bonus for the specific moment /// @param timestamp Time of investment (in seconds)
function getBonus(uint timestamp) public constant returns (uint) { if (timestamp > endDate) { throw; } if (startDate > timestamp) { return 1499; // 49.9% } uint icoDuration = timestamp - startDate; if (icoDuration >= 16 days) { return 1000; // 0% } else if (icoDuration >= 9 days) { return 1125; // 12.5% } else if (icoDuration >= 2 days) { return 1250; // 25% } else { return 1499; // 49.9% } }
0.4.8
/// @dev Issues tokens for users who made BTC purchases. /// @param beneficiary Address the tokens will be issued to. /// @param investment Invested amount in Wei /// @param timestamp Time of investment (in seconds)
function fixInvestment(address beneficiary, uint investment, uint timestamp) external onlyFounder minInvestment(investment) returns (uint) { // Calculate number of tokens to mint uint tokenCount = calculateTokens(investment, timestamp); // Update fund's and user's balance and total supply of tokens. tokensDistributed = add(tokensDistributed, tokenCount); // Distribute tokens. if (!humaniqToken.transferFrom(allocationAddress, beneficiary, tokenCount)) { // Tokens could not be issued. throw; } return tokenCount; }
0.4.8
// change restricted releaseXX account
function changeReleaseAccount(address _owner, address _newowner) internal returns (bool) { require(balances[_newowner] == 0); require(releaseTime[_owner] != 0 ); require(releaseTime[_newowner] == 0 ); balances[_newowner] = balances[_owner]; releaseTime[_newowner] = releaseTime[_owner]; balances[_owner] = 0; releaseTime[_owner] = 0; return true; }
0.4.21
/** * @dev Function to mint tokens * @param _to The address that will recieve the minted tokens. * @param _amount The amount of tokens to mint. * @param _releaseTime The (optional) freeze time - KYC & bounty accounts. * @return A boolean that indicates if the operation was successful. */
function mint(address _to, uint256 _amount, uint256 _releaseTime) internal canMint returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); if ( _releaseTime > 0 ) { releaseTime[_to] = _releaseTime; } emit Transfer(0x0, _to, _amount); return true; }
0.4.21
// ETH Course in USD // constructor
function ArconaToken(uint256 _startSale,uint256 _finishSale,address _multisig,address _restricted,address _registerbot,address _certbot, address _release6m, address _release12m, address _release18m) public { multisig = _multisig; restricted = _restricted; registerbot = _registerbot; certbot = _certbot; release6m = _release6m; release12m = _release12m; release18m = _release18m; startSale = _startSale; finishSale = _finishSale; }
0.4.21
// import preICO customers from 0x516130856e743090af9d7fd95d6fc94c8743a4e1
function importCustomer(address _customer, address _referral, uint _tokenAmount) public { require(msg.sender == registerbot || msg.sender == owner); require(_customer != address(0)); require(now < startSale); // before ICO starts registered[_customer] = true; if (_referral != address(0) && _referral != _customer) { referral[_customer] = _referral; } mint(_customer, _tokenAmount, now + 99 * 1 years); // till KYC is completed }
0.4.21
/// @dev vest Detail : second unit
function vestTokensDetailInt( address _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt) external onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS, _cliffS, _durationS, _revocable, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); }
0.4.24
/// @dev vest StartAt : day unit
function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _durationDay ) public onlyOwner { require(_beneficiary != address(0)); uint256 tokensAmount = _tokensAmountInt * 10**uint256(decimals); uint256 afterSec = _afterDay * daySecond; uint256 cliffSec = _cliffDay * daySecond; uint256 durationSec = _durationDay * daySecond; if(vestingOf[_beneficiary] == 0x0) { TokenVesting vesting = new TokenVesting(_beneficiary, _startS + afterSec, cliffSec, durationSec, true, owner); vestingOf[_beneficiary] = address(vesting); } require(this.transferFrom(reserveTokensVault, vestingOf[_beneficiary], tokensAmount)); }
0.4.24
// BTC external payments
function foreignBuy(address _holder, uint256 _weiAmount, uint256 _rate) public { require(msg.sender == registerbot || msg.sender == owner); require(_weiAmount > 0); require(_rate > 0); registered[_holder] = true; uint tokens = _rate.mul(_weiAmount).div(1 ether); mint(_holder, tokens, now + 99 * 1 years); // till KYC is completed totalWeiSale = totalWeiSale.add(_weiAmount); }
0.4.21
/// @notice Function to deposit stablecoins /// @param _amount Amount to deposit /// @param _tokenIndex Type of stablecoin to deposit
function deposit(uint256 _amount, uint256 _tokenIndex) external { require(msg.sender == tx.origin || isTrustedForwarder(msg.sender), "Only EOA or Biconomy"); require(_amount > 0, "Amount must > 0"); uint256 _ETHPrice = _determineETHPrice(_tokenIndex); uint256 _pool = getAllPoolInETH(_ETHPrice); address _sender = _msgSender(); Tokens[_tokenIndex].token.safeTransferFrom(_sender, address(this), _amount); uint256 _amtDeposit = _amount; // For event purpose if (Tokens[_tokenIndex].decimals == 6) { _amount = _amount.mul(1e12); } // Calculate network fee uint256 _networkFeePerc; if (_amount < networkFeeTier2[0]) { // Tier 1 _networkFeePerc = networkFeePerc[0]; } else if (_amount <= networkFeeTier2[1]) { // Tier 2 _networkFeePerc = networkFeePerc[1]; } else if (_amount < customNetworkFeeTier) { // Tier 3 _networkFeePerc = networkFeePerc[2]; } else { // Custom Tier _networkFeePerc = customNetworkFeePerc; } uint256 _fee = _amount.mul(_networkFeePerc).div(DENOMINATOR); _fees = _fees.add(_fee); _amount = _amount.sub(_fee); _balanceOfDeposit[_sender] = _balanceOfDeposit[_sender].add(_amount); uint256 _amountInETH = _amount.mul(_ETHPrice).div(1e18); uint256 _shares = totalSupply() == 0 ? _amountInETH : _amountInETH.mul(totalSupply()).div(_pool); _mint(_sender, _shares); emit Deposit(address(Tokens[_tokenIndex].token), _sender, _amtDeposit, _shares); }
0.7.6
/// @notice Function to invest funds into strategy
function invest() external onlyAdmin { Token memory _USDT = Tokens[0]; Token memory _USDC = Tokens[1]; Token memory _DAI = Tokens[2]; // Transfer out network fees _fees = _fees.div(1e12); // Convert to USDT decimals if (_fees != 0 && _USDT.token.balanceOf(address(this)) > _fees) { uint256 _treasuryFee = _fees.mul(2).div(5); // 40% _USDT.token.safeTransfer(treasuryWallet, _treasuryFee); // 40% _USDT.token.safeTransfer(communityWallet, _treasuryFee); // 40% _USDT.token.safeTransfer(strategist, _fees.sub(_treasuryFee).sub(_treasuryFee)); // 20% emit TransferredOutFees(_fees); _fees = 0; } uint256 _poolInUSD = getAllPoolInUSD().sub(_fees); // Calculation for keep portion of stablecoins and swap remainder to WETH uint256 _toKeepUSDT = _poolInUSD.mul(_USDT.percKeepInVault).div(DENOMINATOR); uint256 _toKeepUSDC = _poolInUSD.mul(_USDC.percKeepInVault).div(DENOMINATOR); uint256 _toKeepDAI = _poolInUSD.mul(_DAI.percKeepInVault).div(DENOMINATOR); _invest(_USDT.token, _toKeepUSDT); _invest(_USDC.token, _toKeepUSDC); _toKeepDAI = _toKeepDAI.mul(1e12); // Follow decimals of DAI _invest(_DAI.token, _toKeepDAI); // Invest all swapped WETH to strategy uint256 _balanceOfWETH = WETH.balanceOf(address(this)); if (_balanceOfWETH > 0) { strategy.invest(_balanceOfWETH); emit ETHToInvest(_balanceOfWETH); } }
0.7.6
/// @notice Function to determine Curve index for swapTokenWithinVault() /// @param _tokenIndex Index of stablecoin /// @return stablecoin index use in Curve
function _determineCurveIndex(uint256 _tokenIndex) private pure returns (int128) { if (_tokenIndex == 0) { return 2; } else if (_tokenIndex == 1) { return 1; } else { return 0; } }
0.7.6
/** * @dev Contract initializer. * @param _logic Address of the initial implementation. * @param _data Data to send as msg.data to the implementation to initialize the proxied contract. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */
function initialize(address _logic, bytes memory _data) public payable { require(_implementation() == address(0)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); if (_data.length > 0) { (bool success, ) = _logic.delegatecall(_data); require(success); } }
0.6.12
/// @notice Function to swap between tokens with Uniswap /// @param _amountIn Amount to swap /// @param _fromToken Token to be swapped /// @param _toToken Token to be received /// @return _amounts Array that contain amount swapped
function _swapExactTokensForTokens(uint256 _amountIn, address _fromToken, address _toToken) private returns (uint256[] memory _amounts) { address[] memory _path = new address[](2); _path[0] = _fromToken; _path[1] = _toToken; uint256[] memory _amountsOut = router.getAmountsOut(_amountIn, _path); if (_amountsOut[1] > 0) { _amounts = router.swapExactTokensForTokens(_amountIn, 0, _path, address(this), block.timestamp); } else { // Not enough amount to swap uint256[] memory _zeroReturn = new uint256[](2); _zeroReturn[0] = 0; _zeroReturn[1] = 0; return _zeroReturn; } }
0.7.6
/// @notice Function to set new network fee for deposit amount tier 2 /// @param _networkFeeTier2 Array that contains minimum and maximum amount of tier 2 (18 decimals)
function setNetworkFeeTier2(uint256[] calldata _networkFeeTier2) external onlyOwner { require(_networkFeeTier2[0] != 0, "Minimun amount cannot be 0"); require(_networkFeeTier2[1] > _networkFeeTier2[0], "Maximun amount must greater than minimun amount"); /** * Network fees have three tier, but it is sufficient to have minimun and maximun amount of tier 2 * Tier 1: deposit amount < minimun amount of tier 2 * Tier 2: minimun amount of tier 2 <= deposit amount <= maximun amount of tier 2 * Tier 3: amount > maximun amount of tier 2 */ uint256[] memory oldNetworkFeeTier2 = networkFeeTier2; networkFeeTier2 = _networkFeeTier2; emit SetNetworkFeeTier2(oldNetworkFeeTier2, _networkFeeTier2); }
0.7.6
/// @notice Function to set new network fee percentage /// @param _networkFeePerc Array that contains new network fee percentage for tier 1, tier 2 and tier 3
function setNetworkFeePerc(uint256[] calldata _networkFeePerc) external onlyOwner { require( _networkFeePerc[0] < 3000 && _networkFeePerc[1] < 3000 && _networkFeePerc[2] < 3000, "Network fee percentage cannot be more than 30%" ); /** * _networkFeePerc content a array of 3 element, representing network fee of tier 1, tier 2 and tier 3 * For example networkFeePerc is [100, 75, 50] * which mean network fee for Tier 1 = 1%, Tier 2 = 0.75% and Tier 3 = 0.5% */ uint256[] memory oldNetworkFeePerc = networkFeePerc; networkFeePerc = _networkFeePerc; emit SetNetworkFeePerc(oldNetworkFeePerc, _networkFeePerc); }
0.7.6
/// @notice Function to migrate all funds from old strategy contract to new strategy contract
function migrateFunds() external onlyOwner { require(unlockTime <= block.timestamp && unlockTime.add(1 days) >= block.timestamp, "Function locked"); require(WETH.balanceOf(address(strategy)) > 0, "No balance to migrate"); require(pendingStrategy != address(0), "No pendingStrategy"); uint256 _amount = WETH.balanceOf(address(strategy)); WETH.safeTransferFrom(address(strategy), pendingStrategy, _amount); // Set new strategy address oldStrategy = address(strategy); strategy = ICitadelStrategy(pendingStrategy); pendingStrategy = address(0); canSetPendingStrategy = true; // Approve new strategy WETH.safeApprove(address(strategy), type(uint256).max); WETH.safeApprove(oldStrategy, 0); unlockTime = 0; // Lock back this function emit MigrateFunds(oldStrategy, address(strategy), _amount); }
0.7.6
/// @notice Function to get exact USD amount of pool in vault /// @return Exact USD amount of pool in vault (no decimals)
function _getVaultPoolInUSD() private view returns (uint256) { uint256 _vaultPoolInUSD = (Tokens[0].token.balanceOf(address(this)).mul(1e12)) .add(Tokens[1].token.balanceOf(address(this)).mul(1e12)) .add(Tokens[2].token.balanceOf(address(this))) .sub(_fees); // In very rare case that fees > vault pool, above calculation will raise error // Use getReimburseTokenAmount() to get some stablecoin from strategy return _vaultPoolInUSD.div(1e18); }
0.7.6
/// @notice Function to determine ETH price based on stablecoin /// @param _tokenIndex Type of stablecoin to determine /// @return Price of ETH (18 decimals)
function _determineETHPrice(uint256 _tokenIndex) private view returns (uint256) { address _priceFeedContract; if (address(Tokens[_tokenIndex].token) == 0xdAC17F958D2ee523a2206206994597C13D831ec7) { // USDT _priceFeedContract = 0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46; // USDT/ETH } else if (address(Tokens[_tokenIndex].token) == 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48) { // USDC _priceFeedContract = 0x986b5E1e1755e3C2440e960477f25201B0a8bbD4; // USDC/ETH } else { // DAI _priceFeedContract = 0x773616E4d11A78F511299002da57A0a94577F1f4; // DAI/ETH } return _getPriceFromChainlink(_priceFeedContract); }
0.7.6
// ----- PUBLIC METHODS ----- // //emits Transfer event
function mintUniqly(uint256 numUniqlies) external payable { require(_saleStarted, "Sale not started yet"); uint256 requiredValue = numUniqlies * _tokenPrice; uint256 mintIndex = totalSupply(); require(msg.value >= requiredValue, "Not enough ether"); require( (numUniqlies + mintIndex) <= _maxUniqly, "You cannot buy that many tokens" ); for (uint256 i = 0; i < numUniqlies; i++) { _safeMint(msg.sender, mintIndex); mintIndex++; } // send back ETH if one overpay by accident if (requiredValue < msg.value) { payable(msg.sender).transfer(msg.value - requiredValue); } }
0.8.6
// ----- OWNERS METHODS ----- //
function getRandomNumber(uint256 adminProvidedSeed) external onlyOwner returns (bytes32) { require(totalSupply() >= _maxUniqly, "Sale must be ended"); require(randomResult == 0, "Random number already initiated"); require(address(this).balance >= 10 ether, "min 10 ETH balance required"); require( LINK.balanceOf(address(this)) >= fee, "Not enough LINK" ); return requestRandomness(keyHash, fee, adminProvidedSeed); }
0.8.6
/** * @dev Returns the current implementation of a proxy. * This is needed because only the proxy admin can query it. * @return The address of the current implementation of the proxy. */
function getProxyImplementation(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("implementation()")) == 0x5c60da1b (bool success, bytes memory returndata) = address(proxy).staticcall(hex"5c60da1b"); require(success); return abi.decode(returndata, (address)); }
0.5.17
/** * @dev Returns the admin of a proxy. Only the admin can query it. * @return The address of the current admin of the proxy. */
function getProxyAdmin(AdminUpgradeabilityProxy proxy) public view returns (address) { // We need to manually run the static call since the getter cannot be flagged as view // bytes4(keccak256("admin()")) == 0xf851a440 (bool success, bytes memory returndata) = address(proxy).staticcall(hex"f851a440"); require(success); return abi.decode(returndata, (address)); }
0.5.17
/* * @dev Withdraws the contracts balance to owner and DAO. */
function withdraw() public onlyOwner { // Reserve 30% for DAO treasury (bool hs, ) = payable(DAO_TREASURY_ADDRESS).call{ value: (address(this).balance * 30) / 100 }(""); require(hs, "DAO tranfer failed"); // owner only (bool os, ) = payable(owner()).call{ value: address(this).balance }(""); require(os, "owner transfer failed"); }
0.8.11
/* * @dev Mints doggos when presale is enabled. */
function presaleMintDoggo(uint256 quantity, bytes32[] calldata merkleProof) external payable whenNotPaused whenPreSale nonReentrant { require(totalSupply() + quantity < MAX_SUPPLY, "max supply reached"); if (_msgSender() != owner()) { require(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, "max public supply reached"); require( MerkleProof.verify(merkleProof, PRE_SALE_MERKLE_ROOT, keccak256(abi.encodePacked(_msgSender()))), "Address not on the list" ); require(_numberMinted(_msgSender()) + quantity <= PRE_SALE_MAX_MINT_AMOUNT, "presale mint limit reached"); require(msg.value >= COST * quantity, "incorrect ether value"); } _mintDoggo(_msgSender(), quantity); }
0.8.11
/* * @dev Mints doggos when presale is disabled. */
function mintDoggo(uint256 quantity) external payable whenNotPaused whenNotPreSale nonReentrant { require(totalSupply() + quantity < MAX_SUPPLY, "max supply reached"); if (_msgSender() != owner()) { require(totalSupply() + quantity < MAX_PUBLIC_SUPPLY, "max public supply reached"); require(_numberMinted(_msgSender()) + quantity <= MAX_MINT_AMOUNT, "mint limit reached"); require(msg.value >= COST * quantity, "incorrect ether value"); } _mintDoggo(_msgSender(), quantity); }
0.8.11
/** * @dev schedule lock */
function scheduleLock( Direction _restriction, uint256 _startAt, uint256 _endAt, bool _scheduleInverted) public onlyAuthority returns (bool) { require(_startAt <= _endAt, "LOR02"); lock = ScheduledLock( _restriction, _startAt, _endAt, _scheduleInverted ); emit LockDefinition( lock.restriction, lock.startAt, lock.endAt, lock.scheduleInverted); }
0.4.24
// Dutch-ish Auction
function currentPrice(uint256 tulipNumber) public view returns (uint256 price) { if (tulipNumber == latestNewTulipForSale) { // if currently in auction uint256 initialPrice = 1000 ether; uint256 decayPeriod = 1 days; // price = initial_price - initial_price * (current_time - start_time) / decay_period uint256 elapsedTime = block.timestamp - tulips[tulipNumber].listingTime; if (elapsedTime >= decayPeriod) return 0; return initialPrice - ((initialPrice * elapsedTime) / decayPeriod); } else { // if not in auction return tulips[tulipNumber].price; } }
0.8.7
//0: not revealed, 1: cat 2: tiger
function checkSpecies(uint256 _tokenId) public view returns (uint256){ if(_secret == 0 || !_exists(_tokenId)){ return 0; } if(evolved[_tokenId]){ return 2; } uint256 rand = uint256(keccak256(abi.encodePacked(_tokenId, _secret))); if(rand % 3 == 0){ return 2; }else{ return 1; } }
0.8.6
/** * Sets series limit. * * @param series series name * @param limit limit of the tokens that can be under this series * @param mintPrice price to mint the token */
function setSeries(string memory series, uint256 limit, uint256 mintPrice) public onlyOwner { require(bytes(series).length > bytes("").length, "series cannot be empty string"); _seriesLimits[series] = limit; _seriesMintPrices[series] = mintPrice; emit SeriesSet(msg.sender, series, limit, mintPrice); }
0.8.4
/** * Mints the token with predictions. This method will produce the logs so the user can find out the tokenId once transaction is written to the chain. * * @param series series name * @param nickname space for user to put the identifier * @param predict_1 prediction 1 * @param predict_2 prediction 2 * @param predict_3 prediction 3 * @param predict_4 prediction 4 * @param predict_5 prediction 5 * @param predict_6 prediction 6 * */
function mint(string memory series, string memory nickname, uint64 predict_1, uint64 predict_2, uint64 predict_3, uint64 predict_4, uint64 predict_5, uint64 predict_6) public payable { require(_seriesMints[series] < _seriesLimits[series], "Series limit has been reached"); require(msg.value == _seriesMintPrices[series], "ETH value does not match the series mint price"); bytes memory b = new bytes(0); _mint(msg.sender, _numTokens, 1, b); uint64 luck = generateLuckyNum(_numTokens, _numDecimals); uint256 seriesNumber = _seriesMints[series] + 1; _predictions[_numTokens] = Prediction(block.timestamp, series, seriesNumber, nickname, luck, predict_1, predict_2, predict_3, predict_4, predict_5, predict_6); emit PredictionMinted(msg.sender, _numTokens, series, seriesNumber, nickname, luck, predict_1, predict_2, predict_3, predict_4, predict_5, predict_6); _numTokens = _numTokens + 1; _seriesMints[series] = seriesNumber; }
0.8.4
/** * * Sets the result for the given token. * * @param tokenId token id * @param result_0 the actual value at the time of when prediction had been written to the chain * @param result_1 the actual value to the prediction_1 * @param result_2 the actual value to the prediction_2 * @param result_3 the actual value to the prediction_3 * @param result_4 the actual value to the prediction_4 * @param result_5 the actual value to the prediction_5 * @param result_6 the actual value to the prediction_6 */
function setResult(uint256 tokenId, uint64 result_0, uint64 result_1, uint64 result_2, uint64 result_3, uint64 result_4, uint64 result_5, uint64 result_6) public onlyOwner { require(bytes(_predictions[tokenId].series).length > bytes("").length, "prediction must be minted before result can be set"); _results[tokenId] = Result(result_0, result_1, result_2, result_3, result_4, result_5, result_6); emit ResultSet(msg.sender, tokenId, _predictions[tokenId].series, result_0, result_1, result_2, result_3, result_4, result_5, result_6); }
0.8.4
/** * Returns the result data under the specified token. * * @param tokenId token id * @return result data for the given token */
function result(uint256 tokenId) public view returns (ScoredResult memory) { uint64 score_1 = calculateScore(_predictions[tokenId].predict_1, _results[tokenId].result_1, _numDecimals); uint64 score_2 = calculateScore(_predictions[tokenId].predict_2, _results[tokenId].result_2, _numDecimals); uint64 score_3 = calculateScore(_predictions[tokenId].predict_3, _results[tokenId].result_3, _numDecimals); uint64 score_4 = calculateScore(_predictions[tokenId].predict_4, _results[tokenId].result_4, _numDecimals); uint64 score_5 = calculateScore(_predictions[tokenId].predict_5, _results[tokenId].result_5, _numDecimals); uint64 score_6 = calculateScore(_predictions[tokenId].predict_6, _results[tokenId].result_6, _numDecimals); uint64 totalScore = calculateTotalScore(score_1, score_2, score_3, score_4, score_5, score_6); return ScoredResult(totalScore, _results[tokenId].result_0, _results[tokenId].result_1, score_1, _results[tokenId].result_2, score_2, _results[tokenId].result_3, score_3, _results[tokenId].result_4, score_4, _results[tokenId].result_5, score_5, _results[tokenId].result_6, score_6); }
0.8.4
/** * Generates lucky number. This is a pseudo random number. This is 0-100% (bounds included), with the given number of decimals. * * @param seed seed number * @param nd number of decimal points to work with * @return generated number */
function generateLuckyNum(uint256 seed, uint8 nd) internal pure returns (uint64) { uint256 fact = (100 * (10**nd)) + 1; uint256 kc = uint256(keccak256(abi.encodePacked(seed))); uint256 rn = kc % fact; return uint64(rn); }
0.8.4
/** * Calculates score from prediction and results. * * @param pred preduction * @param res the actual value * @param nd number of decimal points * @return calculated score as 0-100% witgh decimals */
function calculateScore(uint64 pred, uint64 res, uint8 nd) internal pure returns (uint64) { if (pred == 0 && res == 0) { return 0; } uint256 fact = 10**nd; if (pred >= res) { uint256 p2 = pred; uint256 r2 = 100 * res * fact; uint256 r = r2 / p2; return uint64(r); } else { uint256 p2 = 100 * pred * fact; uint256 r2 = res; uint256 r = p2 / r2; return uint64(r); } }
0.8.4
/** * Calculates total score from the 6 scores. * * @param s1 score 1 * @param s2 score 2 * @param s3 score 3 * @param s4 score 4 * @param s5 score 5 * @param s6 score 6 * @return total score as a weigted average */
function calculateTotalScore(uint64 s1, uint64 s2, uint64 s3, uint64 s4, uint64 s5, uint64 s6) internal pure returns (uint64) { uint256 s1a = s1 * 11; uint256 s2a = s2 * 12; uint256 s3a = s3 * 13; uint256 s4a = s4 * 14; uint256 s5a = s5 * 15; uint256 s6a = s6 * 16; uint256 res = (s1a + s2a + s3a + s4a + s5a + s6a) / 81; return uint64(res); }
0.8.4
/** * Concatenates strings. * * @param a string a * @param b string b * @return concatenateds string */
function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory ba = bytes(a); bytes memory bb = bytes(b); string memory ab = new string(ba.length + bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < ba.length; i++) bab[k++] = ba[i]; for (uint i = 0; i < bb.length; i++) bab[k++] = bb[i]; return string(bab); }
0.8.4
// Constructor function, initializes the contract and sets the core variables
function Exchange(address feeAccount_, uint256 makerFee_, uint256 takerFee_, address exchangeContract_, address DmexOracleContract_) { owner = msg.sender; feeAccount = feeAccount_; makerFee = makerFee_; takerFee = takerFee_; exchangeContract = exchangeContract_; DmexOracleContract = DmexOracleContract_; }
0.4.25
// This function allows the user to manually release collateral in case the oracle service does not provide the price during the inactivityReleasePeriod
function forceReleaseReserve (bytes32 futuresContract, bool side) public { if (futuresContracts[futuresContract].expirationBlock == 0) throw; if (futuresContracts[futuresContract].expirationBlock > block.number) throw; if (safeAdd(futuresContracts[futuresContract].expirationBlock, DMEX_Base(exchangeContract).getInactivityReleasePeriod()) > block.number) throw; bytes32 positionHash = keccak256(this, msg.sender, futuresContract, side); if (retrievePosition(positionHash)[1] == 0) throw; futuresContracts[futuresContract].broken = true; uint256[4] memory pos = retrievePosition(positionHash); FuturesContract cont = futuresContracts[futuresContract]; address baseToken = futuresAssets[cont.asset].baseToken; uint256 reservedFunding = calculateFundingCost(pos[1], pos[0], safeSub(cont.expirationBlock, pos[3]+1), futuresContract); uint256 collateral; if (side) { collateral = calculateCollateral(cont.floorPrice, pos[1], pos[0], true, futuresContract); subReserve( baseToken, msg.sender, DMEX_Base(exchangeContract).getReserve(baseToken, msg.sender), safeAdd(reservedFunding, collateral) ); } else { collateral = calculateCollateral(cont.capPrice, pos[1], pos[0], false, futuresContract); subReserve( baseToken, msg.sender, DMEX_Base(exchangeContract).getReserve(baseToken, msg.sender), safeAdd(reservedFunding, collateral) ); } updatePositionSize(positionHash, 0, 0); emit FuturesForcedRelease(futuresContract, side, msg.sender); }
0.4.25
// Settle positions for closed contracts
function batchSettlePositions ( bytes32[] futuresContracts, bool[] sides, address[] users, uint256 gasFeePerClose // baseToken with 8 decimals ) onlyAdmin { for (uint i = 0; i < futuresContracts.length; i++) { closeFuturesPositionForUser(futuresContracts[i], sides[i], users[i], gasFeePerClose); } }
0.4.25
/// @inheritdoc IUniswapV3SwapCallback
function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes memory path ) external view override { require(amount0Delta > 0 || amount1Delta > 0); // swaps entirely within 0-liquidity regions are not supported (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); CallbackValidation.verifyCallback(factory, tokenIn, tokenOut, fee); (bool isExactInput, uint256 amountToPay, uint256 amountReceived) = amount0Delta > 0 ? (tokenIn < tokenOut, uint256(amount0Delta), uint256(-amount1Delta)) : (tokenOut < tokenIn, uint256(amount1Delta), uint256(-amount0Delta)); if (isExactInput) { assembly { let ptr := mload(0x40) mstore(ptr, amountReceived) revert(ptr, 32) } } else { // if the cache has been populated, ensure that the full output amount has been received if (amountOutCached != 0) require(amountReceived == amountOutCached); assembly { let ptr := mload(0x40) mstore(ptr, amountToPay) revert(ptr, 32) } } }
0.7.6
/// @dev Parses a revert reason that should contain the numeric quote
function parseRevertReason(bytes memory reason) private pure returns (uint256) { if (reason.length != 32) { if (reason.length < 68) revert('Unexpected error'); assembly { reason := add(reason, 0x04) } revert(abi.decode(reason, (string))); } return abi.decode(reason, (uint256)); }
0.7.6
/// @inheritdoc IQuoter
function quoteExactInputSingle( address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint160 sqrtPriceLimitX96 ) public override returns (uint256 amountOut) { bool zeroForOne = tokenIn < tokenOut; try getPool(tokenIn, tokenOut, fee).swap( address(this), // address(0) might cause issues with some tokens zeroForOne, amountIn.toInt256(), sqrtPriceLimitX96 == 0 ? (zeroForOne ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1) : sqrtPriceLimitX96, abi.encodePacked(tokenIn, fee, tokenOut) ) {} catch (bytes memory reason) { return parseRevertReason(reason); } }
0.7.6
/** * @dev Deposit ETH/ERC20 and mint Compound Tokens */
function mintCETH(uint ethAmt) internal { if (ethAmt > 0) { CETHInterface cToken = CETHInterface(cEth); cToken.mint.value(ethAmt)(); uint exchangeRate = CTokenInterface(cEth).exchangeRateCurrent(); uint cEthToReturn = wdiv(ethAmt, exchangeRate); cEthToReturn = wmul(cEthToReturn, exchangeRate) <= ethAmt ? cEthToReturn : cEthToReturn - 1; require(cToken.transfer(msg.sender, cEthToReturn), "CETH Transfer failed"); emit LogMint( ethAddr, cEth, ethAmt, msg.sender ); } }
0.5.8
/** * @dev If col/debt > user's balance/borrow. Then set max */
function checkCompound(uint ethAmt, uint daiAmt) internal returns (uint ethCol, uint daiDebt) { CTokenInterface cEthContract = CTokenInterface(cEth); uint cEthBal = cEthContract.balanceOf(msg.sender); uint ethExchangeRate = cEthContract.exchangeRateCurrent(); ethCol = wmul(cEthBal, ethExchangeRate); ethCol = wdiv(ethCol, ethExchangeRate) <= cEthBal ? ethCol : ethCol - 1; ethCol = ethCol <= ethAmt ? ethCol : ethAmt; // Set Max if amount is greater than the Col user have daiDebt = CDAIInterface(cDai).borrowBalanceCurrent(msg.sender); daiDebt = daiDebt <= daiAmt ? daiDebt : daiAmt; // Set Max if amount is greater than the Debt user have }
0.5.8
/** * @dev Deposit DAI for liquidity */
function depositDAI(uint amt) public { require(ERC20Interface(daiAddr).transferFrom(msg.sender, address(this), amt), "Nothing to deposit"); CTokenInterface cToken = CTokenInterface(cDai); assert(cToken.mint(amt) == 0); uint exchangeRate = cToken.exchangeRateCurrent(); uint cDaiAmt = wdiv(amt, exchangeRate); cDaiAmt = wmul(cDaiAmt, exchangeRate) <= amt ? cDaiAmt : cDaiAmt - 1; deposits[msg.sender] += cDaiAmt; totalDeposits += cDaiAmt; }
0.5.8
/** * @dev Withdraw DAI from liquidity */
function withdrawDAI(uint amt) public { require(deposits[msg.sender] != 0, "Nothing to Withdraw"); CTokenInterface cToken = CTokenInterface(cDai); uint exchangeRate = cToken.exchangeRateCurrent(); uint withdrawAmt = wdiv(amt, exchangeRate); uint daiAmt = amt; if (withdrawAmt > deposits[msg.sender]) { withdrawAmt = deposits[msg.sender]; daiAmt = wmul(withdrawAmt, exchangeRate); } require(cToken.redeem(withdrawAmt) == 0, "something went wrong"); require(ERC20Interface(daiAddr).transfer(msg.sender, daiAmt), "Dai Transfer failed"); deposits[msg.sender] -= withdrawAmt; totalDeposits -= withdrawAmt; }
0.5.8
/** * @dev Withdraw CDAI from liquidity */
function withdrawCDAI(uint amt) public { require(deposits[msg.sender] != 0, "Nothing to Withdraw"); uint withdrawAmt = amt; if (withdrawAmt > deposits[msg.sender]) { withdrawAmt = deposits[msg.sender]; } require(CTokenInterface(cDai).transfer(msg.sender, withdrawAmt), "Dai Transfer failed"); deposits[msg.sender] -= withdrawAmt; totalDeposits -= withdrawAmt; }
0.5.8
/** * collecting fees generated overtime */
function withdrawFeesInCDai(uint num) public { CTokenInterface cToken = CTokenInterface(cDai); uint cDaiBal = cToken.balanceOf(address(this)); uint withdrawAmt = sub(cDaiBal, totalDeposits); if (num == 0) { require(cToken.transfer(feeOne, withdrawAmt), "Dai Transfer failed"); } else { require(cToken.transfer(feeTwo, withdrawAmt), "Dai Transfer failed"); } }
0.5.8
/** * Whitelist Many user address at once - only Owner can do this * It will require maximum of 150 addresses to prevent block gas limit max-out and DoS attack * It will add user address in whitelisted mapping */
function whitelistManyUsers(address[] memory userAddresses) onlyOwner public{ require(whitelistingStatus == true); uint256 addressCount = userAddresses.length; require(addressCount <= 150); for(uint256 i = 0; i < addressCount; i++){ require(userAddresses[i] != address(0x0)); whitelisted[userAddresses[i]] = true; } }
0.4.25
/** * @dev MakerDAO to Compound */
function makerToCompound(uint cdpId, uint ethCol, uint daiDebt) public payable isUserWallet returns (uint daiAmt) { uint ethAmt; (ethAmt, daiAmt) = checkCDP(bytes32(cdpId), ethCol, daiDebt); daiAmt = wipeAndFree(cdpId, ethAmt, daiAmt); daiAmt = wmul(daiAmt, 1002000000000000000); // 0.2% fees mintCETH(ethAmt); give(cdpId, msg.sender); }
0.5.8