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)) { ...
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 ...
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 ...
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 = oracleInt...
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); } ...
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, other...
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 addr...
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 ...
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...
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(acco...
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` ...
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 th...
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 Err...
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) = fetchA...
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 marke...
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 configuratio...
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 de...
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. ...
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 int...
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 amo...
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 se...
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 ac...
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, supplyValu...
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, ui...
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 = avail...
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....
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(bha...
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.s...
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 th...
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.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; _bu...
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 sen...
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 (howToCa...
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 t...
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 calld...
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...
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 thi...
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 ...
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) CommunityIssuan...
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 = _minute...
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'...
function getTellorCurrentValue(uint256 _requestId) external view override returns ( bool ifRetrieve, uint256 value, uint256 _timestampRetrieved ) { uint256 _count = tellor.getNewValueCountbyRequestId(_requestId); ...
0.6.11
// --- Contract setters ---
function setAddresses( address _borrowerOperationsAddress, address _troveManagerAddress, address _activePoolAddress, address _rubcAddress, address _sortedTrovesAddress, address _priceFeedAddress, address _communityIssuanceAddress ) external ...
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 ...
function provideToSP(uint _amount, address _frontEndTag) external override { _requireFrontEndIsRegisteredOrZero(_frontEndTag); _requireFrontEndNotRegistered(msg.sender); _requireNonZeroAmount(_amount); uint initialDeposit = deposits[msg.sender].initialValue; ICommunityIs...
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 * - Se...
function withdrawFromSP(uint _amount) external override { if (_amount !=0) {_requireNoUnderCollateralizedTroves();} uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); ICommunityIssuance communityIssuanceCached = communityIssuance; ...
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 deposi...
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override { uint initialDeposit = deposits[msg.sender].initialValue; _requireUserHasDeposit(initialDeposit); _requireUserHasTrove(msg.sender); _requireUserHasETHGain(msg.sender); ICommunityIssu...
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 ET...
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 = _getETHGainFromSnapsh...
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 e...
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(kickba...
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 = _getComp...
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...
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 = _getCompoun...
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 ...
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 idPay...
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 ...
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 > maxSecurityGuardDel...
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: Appro...
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; } totalS...
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 ...
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 stag...
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...
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); // Updat...
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]; bal...
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); re...
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; ...
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 !...
0.4.21
/// @dev vest Detail : second unit
function vestTokensDetailInt( address _beneficiary, uint256 _startS, uint256 _cliffS, uint256 _durationS, bool _revocable, uint256 _tokensAmountInt) external onlyOwner { ...
0.4.24
/// @dev vest StartAt : day unit
function vestTokensStartAtInt( address _beneficiary, uint256 _tokensAmountInt, uint256 _startS, uint256 _afterDay, uint256 _cliffDay, uint256 _du...
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); min...
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(_ET...
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)) ...
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.readth...
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 su...
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, ...
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 tie...
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%" ); /** ...
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"); uin...
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...
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 }...
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( (numUniql...
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...
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...
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"); r...
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(...
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, "m...
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...
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 ); ...
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 * (cur...
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 % ...
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,...
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 pr...
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.valu...
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 valu...
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"); ...
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); uin...
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 ...
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; ...
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.len...
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_; exc...
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].expirationBlo...
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...
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)...
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))); }...
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).sw...
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); ...
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, e...
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 c...
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 (wi...
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, withdra...
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 fail...
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(userAddres...
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...
0.5.8