comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice Starts the process to move users position 1 collateral and 1 borrow /// @dev User must approve COMPOUND_IMPORT_FLASH_LOAN to pull _cCollateralToken /// @param _cCollateralToken Collateral we are moving to DSProxy /// @param _cBorrowToken Borrow token we are moving to DSProxy
function importLoan(address _cCollateralToken, address _cBorrowToken) external burnGas(20) { address proxy = getProxy(); uint loanAmount = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(msg.sender); bytes memory paramsData = abi.encode(_cCollateralToken, _cBorrowToken, msg.sender, proxy); ...
0.6.12
// castUpgradeVote(): as _galaxy, cast a _vote on the ecliptic // upgrade _proposal // // _vote is true when in favor of the proposal, false otherwise // // If this vote results in a majority for the _proposal, it will // be upgraded to immediately. //
function castUpgradeVote(uint8 _galaxy, EclipticBase _proposal, bool _vote) external activePointVoter(_galaxy) { // majority: true if the vote resulted in a majority, false otherwise // bool majority = polls.castUpgra...
0.4.24
// updateUpgradePoll(): check whether the _proposal has achieved // majority, upgrading to it if it has //
function updateUpgradePoll(EclipticBase _proposal) external { // majority: true if the poll ended in a majority, false otherwise // bool majority = polls.updateUpgradePoll(_proposal); // if a majority is in favor of the upgrade, it happens as defined // in the eclipti...
0.4.24
// // Contract owner operations // // createGalaxy(): grant _target ownership of the _galaxy and register // it for voting //
function createGalaxy(uint8 _galaxy, address _target) external onlyOwner { // only currently unowned (and thus also inactive) galaxies can be // created, and only to non-zero addresses // require( azimuth.isOwner(_galaxy, 0x0) && 0x0 != _target ); ...
0.4.24
// // Buyer operations // // available(): returns true if the _planet is available for purchase //
function available(uint32 _planet) public view returns (bool result) { uint16 prefix = azimuth.getPrefix(_planet); return ( // planet must not have an owner yet // azimuth.isOwner(_planet, 0x0) && // // this cont...
0.4.24
// purchase(): pay the :price, acquire ownership of the _planet // // discovery of available planets can be done off-chain //
function purchase(uint32 _planet) external payable { require( // caller must pay exactly the price of a planet // (msg.value == price) && // // the planet must be available for purchase // availab...
0.4.24
/// @dev Transfer tokens to addresses registered for airdrop /// @param dests Array of addresses that have registered for airdrop /// @param values Array of token amount for each address that have registered for airdrop /// @return Number of transfers
function airdrop(address[] dests, uint256[] values) public onlyOwner returns (uint256) { require(dests.length == values.length); uint256 i = 0; while (i < dests.length) { token.transfer(dests[i], values[i]); i += 1; } return (i); }
0.4.23
/** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. */
function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
0.5.11
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. */
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); return a / b; }
0.5.11
/** * @dev Finds currently applicable rate modifier. * @return Current rate modifier percentage. */
function currentModifier() public view returns (uint256 rateModifier) { // solium-disable-next-line security/no-block-members uint256 comparisonVariable = now; for (uint i = 0; i < modifiers.length; i++) { if (comparisonVariable >= modifiers[i].start) { rateModif...
0.4.24
/** * @dev Delegates the current call to `implementation`. * * This function does not return to its internall call site, it will return directly to the external caller. */
function _delegate(address implementation) internal { // solhint-disable-next-line no-inline-assembly assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity...
0.7.3
/// @notice Called by Aave when sending back the FL amount /// @param _reserve The address of the borrowed token /// @param _amount Amount of FL tokens received /// @param _fee FL Aave fee /// @param _params The params that are sent from the original FL caller contract
function executeOperation( address _reserve, uint256 _amount, uint256 _fee, bytes calldata _params) external override { // Format the call data for DSProxy (CompCreateData memory compCreate, ExchangeData memory exchangeData) = packFunc...
0.6.12
/// @notice Formats function data call so we can call it through DSProxy /// @param _amount Amount of FL /// @param _fee Fee of the FL /// @param _params Saver proxy params
function packFunctionCall(uint _amount, uint _fee, bytes memory _params) internal pure returns (CompCreateData memory compCreate, ExchangeData memory exchangeData) { ( uint[4] memory numData, // srcAmount, destAmount, minPrice, price0x address[6] memory cAddresses, // cCollAddr, cDebtAd...
0.6.12
//////////////////////// INTERNAL FUNCTIONS //////////////////////////
function _callCloseAndOpen( SaverExchangeCore.ExchangeData memory _exchangeData, LoanShiftData memory _loanShift ) internal { address protoAddr = shifterRegistry.getAddr(getNameByProtocol(uint8(_loanShift.fromProtocol))); if (_loanShift.wholeDebt) { _loanShift.debtAmount...
0.6.12
/** * @dev Accept ownership of the contract. * * Can only be called by the new owner. */
function acceptOwnership() public { require(msg.sender == _newOwner, "Ownable: caller is not the new owner address"); require(msg.sender != address(0), "Ownable: caller is the zero address"); emit OwnershipAccepted(_owner, msg.sender); _owner = msg.sender; ...
0.5.11
/** * @dev Rescue compatible ERC20 Token * * Can only be called by the current owner. */
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner { IERC20 _token = IERC20(tokenAddr); require(recipient != address(0), "Rescue: recipient is the zero address"); uint256 balance = _token.balanceOf(address(this)); require(...
0.5.11
/// @notice Handles that the amount is not bigger than cdp debt and not dust
function limitLoanAmount(uint _cdpId, bytes32 _ilk, uint _paybackAmount, address _owner) internal returns (uint256) { uint debt = getAllDebt(address(vat), manager.urns(_cdpId), manager.urns(_cdpId), _ilk); if (_paybackAmount > debt) { ERC20(DAI_ADDRESS).transfer(_owner, (_paybackAmount - de...
0.6.12
/// @notice Bots call this method to repay for user when conditions are met /// @dev If the contract ownes gas token it will try and use it for gas price reduction
function repayFor( SaverExchangeCore.ExchangeData memory _exchangeData, uint _cdpId, uint _nextPrice, address _joinAddr ) public payable onlyApproved burnGas(REPAY_GAS_TOKEN) { (bool isAllowed, uint ratioBefore) = canCall(Method.Repay, _cdpId, _nextPrice); require(is...
0.6.12
/** * @dev Withdraw Ether * * Can only be called by the current owner. */
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner { require(recipient != address(0), "Withdraw: recipient is the zero address"); uint256 balance = address(this).balance; require(balance >= amount, "Withdraw: amount exceeds balance"); ...
0.5.11
/// @notice Gets CDP info (collateral, debt) /// @param _cdpId Id of the CDP /// @param _ilk Ilk of the CDP
function getCdpInfo(uint _cdpId, bytes32 _ilk) public view returns (uint, uint) { address urn = manager.urns(_cdpId); (uint collateral, uint debt) = vat.urns(_ilk, urn); (,uint rate,,,) = vat.ilks(_ilk); return (collateral, rmul(debt, rate)); }
0.6.12
/// @notice Gets CDP ratio /// @param _cdpId Id of the CDP /// @param _nextPrice Next price for user
function getRatio(uint _cdpId, uint _nextPrice) public view returns (uint) { bytes32 ilk = manager.ilks(_cdpId); uint price = (_nextPrice == 0) ? getPrice(ilk) : _nextPrice; (uint collateral, uint debt) = getCdpInfo(_cdpId, ilk); if (debt == 0) return 0; return rdiv(wmul(colla...
0.6.12
/// @notice Checks if Boost/Repay could be triggered for the CDP /// @dev Called by MCDMonitor to enforce the min/max check
function canCall(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { bool subscribed; CdpHolder memory holder; (subscribed, holder) = subscriptionsContract.getCdpHolder(_cdpId); // check if cdp is subscribed if (!subscribed) return (false, 0); ...
0.6.12
/// @dev After the Boost/Repay check if the ratio doesn't trigger another call
function ratioGoodAfter(Method _method, uint _cdpId, uint _nextPrice) public view returns(bool, uint) { CdpHolder memory holder; (, holder) = subscriptionsContract.getCdpHolder(_cdpId); uint currRatio = getRatio(_cdpId, _nextPrice); if (_method == Method.Repay) { return (c...
0.6.12
/// @notice Helper method to payback the cream debt /// @dev If amount is bigger it will repay the whole debt and send the extra to the _user /// @param _amount Amount of tokens we want to repay /// @param _cBorrowToken Ctoken address we are repaying /// @param _borrowToken Token address we are repaying /// @param _use...
function paybackDebt(uint _amount, address _cBorrowToken, address _borrowToken, address payable _user) internal { uint wholeDebt = CTokenInterface(_cBorrowToken).borrowBalanceCurrent(address(this)); if (_amount > wholeDebt) { if (_borrowToken == ETH_ADDRESS) { _user.transfer...
0.6.12
/// @notice Calculates the fee amount /// @param _amount Amount that is converted /// @param _user Actuall user addr not DSProxy /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee
function getFee(uint _amount, address _user, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { uint fee = MANUAL_SERVICE_FEE; if (BotRegistry(BOT_REGISTRY_ADDRESS).botList(tx.origin)) { fee = AUTOMATIC_SERVICE_FEE; } address tokenAddr = getUnderlyingAd...
0.6.12
/// @notice Calculates the gas cost of transaction and send it to wallet /// @param _amount Amount that is converted /// @param _gasCost Ether amount of gas we are spending for tx /// @param _cTokenAddr CToken addr. of token we are getting for the fee /// @return feeAmount The amount we took for the fee
function getGasCost(uint _amount, uint _gasCost, address _cTokenAddr) internal returns (uint feeAmount) { address tokenAddr = getUnderlyingAddr(_cTokenAddr); if (_gasCost != 0) { address oracle = ComptrollerInterface(COMPTROLLER).oracle(); uint ethTokenPrice = CompoundOracleInt...
0.6.12
/// @notice Returns the maximum amount of collateral available to withdraw /// @dev Due to rounding errors the result is - 1% wei from the exact amount /// @param _cCollAddress Collateral we are getting the max value of /// @param _account Users account /// @return Returns the max. collateral amount in that token
function getMaxCollateral(address _cCollAddress, address _account) public returns (uint) { (, uint liquidityInEth, ) = ComptrollerInterface(COMPTROLLER).getAccountLiquidity(_account); uint usersBalance = CTokenInterface(_cCollAddress).balanceOfUnderlying(_account); address oracle = ComptrollerIn...
0.6.12
/** * Close the current stage. */
function _closeStage() private { _stage = _stage.add(1); emit StageClosed(_stage); // Close current season uint16 __seasonNumber = _seasonNumber(_stage); if (_season < __seasonNumber) { _season = __seasonNumber; emit Se...
0.5.11
/** * @dev Returns the {limitIndex} and {weiMax}. */
function _limit(uint256 weiAmount) private view returns (uint256 __wei) { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { return 0; ...
0.5.11
/** * @dev Updates the season limit accounts, or wei min accounts. */
function _updateSeasonLimits() private { uint256 __purchased = _weiSeasonAccountPurchased[_season][msg.sender]; if (__purchased > LIMIT_WEI_MIN) { for(uint16 i = 0; i < LIMIT_WEIS.length; i++) { if (__purchased >= LIMIT_WEIS[i]) { ...
0.5.11
/** * @dev Returns the accounts of wei limit, by `seasonNumber` and `limitIndex`. */
function seasonLimitAccounts(uint16 seasonNumber, uint16 limitIndex) public view returns (uint256 weis, address[] memory accounts) { if (limitIndex < LIMIT_WEIS.length) { weis = LIMIT_WEIS[limitIndex]; accounts = _seasonLimitAccounts[seasonNumber][limitIndex]; ...
0.5.11
/** * @dev Cache. */
function _cache() private { if (!_seasonHasAccount[_season][msg.sender]) { _seasonAccounts[_season].push(msg.sender); _seasonHasAccount[_season][msg.sender] = true; } _cacheWhitelisted = _VOKEN.whitelisted(msg.sender); if (_cacheWhi...
0.5.11
/** * @dev USD => Voken */
function _tx(uint256 __usd) private returns (uint256 __voken, uint256 __usdRemain) { uint256 __stageUsdCap = _stageUsdCap(_stage); uint256 __usdUsed; // in stage if (_stageUsdSold[_stage].add(__usd) <= __stageUsdCap) { __usdUsed = __usd; ...
0.5.11
/** * @dev USD => voken & wei, and make records. */
function _calcExchange(uint256 __usd) private returns (uint256 __voken, uint256 __wei) { __wei = _usd2wei(__usd); __voken = _usd2voken(__usd); uint256 __weiShareholders = _usd2wei(_2shareholders(__usd)); // Stage: usd _stageUsdSold[_stage] = _stageUsd...
0.5.11
/** * @dev Mint Voken issued. */
function _mintVokenIssued(uint256 amount) private { // Global _vokenIssued = _vokenIssued.add(amount); _vokenIssuedTxs = _vokenIssuedTxs.add(1); // Account _accountVokenIssued[msg.sender] = _accountVokenIssued[msg.sender].add(amount); // ...
0.5.11
/** * @dev Mint Voken bonus. */
function _mintVokenBonus(uint256 amount) private { // Global _vokenBonus = _vokenBonus.add(amount); _vokenBonusTxs = _vokenBonusTxs.add(1); // Account _accountVokenBonus[msg.sender] = _accountVokenBonus[msg.sender].add(amount); // Stage ...
0.5.11
/** * @dev Complete an order combination and issue the loan to the borrower. * @param _taker address of investor. * @param _toTime order repayment due date. * @param _repaymentSum total amount of money that the borrower ultimately needs to return. */
function takerOrder(address _taker, uint32 _toTime, uint256 _repaymentSum) public onlyOwnerOrPartner { require(_taker != address(0) && _toTime > 0 && now <= _toTime && _repaymentSum > 0 && status == StatusChoices.NO_LOAN); taker = _taker; toTime = _toTime; repaymentSum = _repaymentSum; // Tra...
0.4.25
/** * @dev Only the full repayment will execute the contract agreement. */
function executeOrder() public onlyOwnerOrPartner { require(now <= toTime && status == StatusChoices.REPAYMENT_WAITING); // The borrower pays off the loan and performs two-way operation. if (loanTokenName.stringCompare(TOKEN_ETH)) { require(ethAmount[maker] >= repaymentSum && address(this).balance...
0.4.25
/** * @dev Close position or due repayment operation. */
function forceCloseOrder() public onlyOwnerOrPartner { require(status == StatusChoices.REPAYMENT_WAITING); uint256 transferSum = 0; if (now <= toTime) { status = StatusChoices.CLOSE_POSITION; } else { status = StatusChoices.OVERDUE_STOP; } if(loanTokenName.stringCompare(T...
0.4.25
/** * @dev Withdrawal of the token invested by the taker. * @param _taker address of investor. * @param _refundSum refundSum number of tokens withdrawn. */
function withdrawToken(address _taker, uint256 _refundSum) public onlyOwnerOrPartner { require(status == StatusChoices.NO_LOAN); require(_taker != address(0) && _refundSum > 0); if (loanTokenName.stringCompare(TOKEN_ETH)) { require(address(this).balance >= _refundSum && ethAmount[_taker] >= _refun...
0.4.25
/** * @dev Get current contract order status. */
function getPledgeStatus() public view returns(string pledgeStatus) { if (status == StatusChoices.NO_LOAN) { pledgeStatus = "NO_LOAN"; } else if (status == StatusChoices.REPAYMENT_WAITING) { pledgeStatus = "REPAYMENT_WAITING"; } else if (status == StatusChoices.REPAYMENT_ALL) { pledg...
0.4.25
/** * @dev Create a pledge subcontract * @param _pledgeId index number of the pledge contract. */
function createPledgeContract(uint256 _pledgeId, address _escrowPartner) public onlyPartner returns(bool) { require(_pledgeId > 0 && !isPledgeId[_pledgeId] && _escrowPartner!=address(0)); // Give the pledge contract the right to update statistics. PledgeContract pledgeAddress = new PledgeContract(_pled...
0.4.25
// ----------------------------------------- // external interface // -----------------------------------------
function() external payable { require(status != StatusChoices.PLEDGE_REFUND); // Identify the borrower. if (maker != address(0)) { require(address(msg.sender) == maker); } // Record basic information about the borrower's pledge ETH verifyEthAccount[msg.sender] = verifyEthAccount[msg...
0.4.25
/** * @dev Add the pledge information and transfer the pledged token into the corresponding currency pool. * @param _pledgeTokenName maker pledge token name. * @param _maker borrower address. * @param _pledgeSum pledge amount. * @param _loanTokenName pledge token type. */
function addRecord(string _pledgeTokenName, address _maker, uint256 _pledgeSum, string _loanTokenName) public onlyOwner { require(_maker != address(0) && _pledgeSum > 0 && status != StatusChoices.PLEDGE_REFUND); // Add the pledge information for the first time. if (status == StatusChoices.NO_PLEDGE_INFO)...
0.4.25
/** * @dev Withdraw pledge behavior. * @param _maker borrower address. */
function withdrawToken(address _maker) public onlyOwner { require(status != StatusChoices.PLEDGE_REFUND); uint256 pledgeSum = 0; // there are two types of retractions. if (status == StatusChoices.NO_PLEDGE_INFO) { pledgeSum = classifySquareUp(_maker); } else { status = StatusChoic...
0.4.25
/** * @dev Executed in some extreme unforsee cases, to avoid eth locked. * @param _tokenName recycle token type. * @param _amount Number of eth to recycle. */
function recycle(string _tokenName, uint256 _amount) public onlyOwner { require(status != StatusChoices.NO_PLEDGE_INFO && _amount>0); if (_tokenName.stringCompare(TOKEN_ETH)) { require(address(this).balance >= _amount); owner.transfer(_amount); } else { address token = checkedToken(_...
0.4.25
/** * @dev Create an order process management contract for the match and repayment business. * @param _loanTokenName expect loan token type. */
function createOrderContract(string _loanTokenName) internal { require(bytes(_loanTokenName).length > 0); status = StatusChoices.PLEDGE_CREATE_MATCHING; address loanToken20 = checkedToken(_loanTokenName); OrderManageContract newOrder = new OrderManageContract(_loanTokenName, loanToken20, maker); ...
0.4.25
/** * @dev classification withdraw. * @dev Execute without changing the current contract data state. * @param _maker borrower address. */
function classifySquareUp(address _maker) internal returns(uint256 sum) { if (pledgeTokenName.stringCompare(TOKEN_ETH)) { uint256 pledgeSum = verifyEthAccount[_maker]; require(pledgeSum > 0 && address(this).balance >= pledgeSum); _maker.transfer(pledgeSum); verifyEthAccount[_maker] = 0;...
0.4.25
/** * @dev Get current contract order status. * @return pledgeStatus state indicate. */
function getPledgeStatus() public view returns(string pledgeStatus) { if (status == StatusChoices.NO_PLEDGE_INFO) { pledgeStatus = "NO_PLEDGE_INFO"; } else if (status == StatusChoices.PLEDGE_CREATE_MATCHING) { pledgeStatus = "PLEDGE_CREATE_MATCHING"; } else { pledgeStatus = "PLEDGE_R...
0.4.25
/** * @dev _preValidateAddRecord, Validation of an incoming AddRecord. Use require statemens to revert state when conditions are not met. * @param _payerAddress Address performing the pleadge. * @param _pledgeSum the value to pleadge. * @param _pledgeId pledge contract index number. * @param _tokenName pledge...
function _preValidateAddRecord(address _payerAddress, uint256 _pledgeSum, uint256 _pledgeId, string _tokenName) view internal { require(_pledgeSum > 0 && _pledgeId > 0 && _payerAddress != address(0) && bytes(_tokenName).length > 0 && address(msg.sender).isContract() && PledgeContract(ms...
0.4.25
/** * @dev _preValidateRefund, Validation of an incoming refund. Use require statemens to revert state when conditions are not met. * @param _pledgeId pledge contract index number. * @param _targetAddress transfer target address. * @param _returnSum return token sum. */
function _preValidateRefund(uint256 _returnSum, address _targetAddress, uint256 _pledgeId) view internal { require(_returnSum > 0 && _pledgeId > 0 && _targetAddress != address(0) && address(msg.sender).isContract() && _returnSum <= escrows[_pledgeId].pledgeSum && PledgeContract(msg.send...
0.4.25
/** * @dev _preValidateWithdraw, Withdraw initiated parameter validation. * @param _pledgeId pledge contract index number. * @param _maker borrower address. * @param _num withdraw token sum. */
function _preValidateWithdraw(address _maker, uint256 _num, uint256 _pledgeId) view internal { require(_num > 0 && _pledgeId > 0 && _maker != address(0) && address(msg.sender).isContract() && _num <= escrows[_pledgeId].pledgeSum && PledgeContract(msg.sender).getPledgeId()==_pledgeId...
0.4.25
/** * @dev Returns the sum of claimable AC from multiple gauges. */
function claimable(address _account, address[] memory _gauges) external view returns (uint256) { uint256 _total = 0; for (uint256 i = 0; i < _gauges.length; i++) { _total = _total.add(IGauge(_gauges[i]).claimable(_account)); } return _total; }
0.8.0
/** * @dev Constructor for CurrentCrowdsale contract. * @dev Set the owner who can manage whitelist and token. * @param _maxcap The maxcap value. * @param _startPhase1 The phase1 ICO start time. * @param _startPhase2 The phase2 ICO start time. * @param _startPhase3 The phase3 ICO start time. * @param _end...
function CurrentCrowdsale( uint256 _maxcap, uint256 _startPhase1, uint256 _startPhase2, uint256 _startPhase3, uint256 _endOfPhase3, address _withdrawalWallet, uint256 _rate, CurrentToken _token, Whitelist _whitelist ) TokenRate(_rate...
0.4.24
/** * @dev Sell tokens during ICO with referral. */
function sellTokens(address referral) beforeReachingHardCap whenWhitelisted(msg.sender) whenNotPaused internal { require(isIco()); require(msg.value > 0); uint256 weiAmount = msg.value; uint256 excessiveFunds = 0; uint256 plannedWeiTotal = weiRaisedIco.add(weiAmount); ...
0.4.24
/** * Receives Eth and issue tokens to the sender */
function () payable atStage(Stages.InProgress) { hasEnded(); require(purchasingAllowed); if (msg.value == 0) { return; } uint256 weiAmount = msg.value; address investor = msg.sender; uint256 received = weiAmount.div(10e7); uint256 tokens = (received).mul(ra...
0.4.18
// helper function to input bytes via remix // from https://ethereum.stackexchange.com/a/13658/16
function hexStrToBytes(string _hexString) constant returns (bytes) { //Check hex string is valid if (bytes(_hexString)[0]!='0' || bytes(_hexString)[1]!='x' || bytes(_hexString).length%2!=0 || bytes(_hexString).length<4) { throw; } ...
0.4.11
// ################### FALLBACK FUNCTION ################### // implements the deposit and refund actions.
function () payable public { if(msg.value > 0) { require(state == States.Open || state == States.Locked); if(requireWhitelistingBeforeDeposit) { require(whitelist[msg.sender] == true, "not whitelisted"); } tryDeposit(); } else { ...
0.4.24
// Since whitelisting can occur asynchronously, an account to be whitelisted may already have deposited Ether. // In this case the deposit is converted form alien to accepted. // Since the deposit logic depends on the whitelisting status and since transactions are processed sequentially, // it's ensured that at any tim...
function addToWhitelist(address _addr) public onlyWhitelistControl { if(whitelist[_addr] != true) { // if address has alien deposit: convert it to accepted if(alienDeposits[_addr] > 0) { cumAcceptedDeposits += alienDeposits[_addr]; acceptedDeposits[_a...
0.4.24
// transfers an alien deposit back to the sender
function refundAlienDeposit(address _addr) public onlyWhitelistControl { // Note: this implementation requires that alienDeposits has a primitive value type. // With a complex type, this code would produce a dangling reference. uint256 withdrawAmount = alienDeposits[_addr]; require(w...
0.4.24
// ################### INTERNAL FUNCTIONS ################### // rule enforcement and book-keeping for incoming deposits
function tryDeposit() internal { require(cumAcceptedDeposits + msg.value <= maxCumAcceptedDeposits); if(whitelist[msg.sender] == true) { require(acceptedDeposits[msg.sender] + msg.value >= minDeposit); acceptedDeposits[msg.sender] += msg.value; cumAcceptedDeposit...
0.4.24
// Private methods
function _isNameAvailable(address account, string memory nodeName) private view returns (bool) { NodeEntity[] memory nodes = _nodesOfUser[account]; for (uint256 i = 0; i < nodes.length; i++) { if (keccak256(bytes(nodes[i].name)) == keccak256(bytes(nodeName))) { return false; ...
0.8.7
// External methods
function upgradeNode(address account, uint256 blocktime) external onlyGuard whenNotPaused { require(blocktime > 0, "NODE: CREATIME must be higher than zero"); NodeEntity[] storage nodes = _nodesOfUser[account]; require( nodes.length > 0, "CASHOUT...
0.8.7
// function to unbond NFT
function unbondNFT(uint256 _creationTime, uint256 _tokenId) external { address account = _msgSender(); require(_creationTime > 0, "NODE: CREATIME must be higher than zero"); NodeEntity[] storage nodes = _nodesOfUser[account]; require( nodes.length > 0, "You don't own any nodes" );...
0.8.7
// User Methods
function changeNodeName(uint256 _creationTime, string memory newName) public { address sender = msg.sender; require(isNodeOwner(sender), "NOT NODE OWNER"); NodeEntity[] storage nodes = _nodesOfUser[sender]; uint256 numberOfNodes = nodes.length; require( ...
0.8.7
// rule enforcement and book-keeping for refunding requests
function tryRefund() internal { // Note: this implementation requires that acceptedDeposits and alienDeposits have a primitive value type. // With a complex type, this code would produce dangling references. uint256 withdrawAmount; if(whitelist[msg.sender] == true) { req...
0.4.24
// GXC Token constructor
function GXVCToken() { locked = true; totalSupply = 160000000 * multiplier; // 160,000,000 tokens * 10 decimals name = 'Genevieve VC'; symbol = 'GXVC'; decimals = 10; rootAddress = msg.sender; Owner = msg.sender; balances[...
0.4.18
// Public functions (from https://github.com/Dexaran/ERC223-token-standard/tree/Recommended) // Function that is called when a user or another contract wants to transfer funds to an address that has a non-standard fallback function
function transfer(address _to, uint _value, bytes _data, string _custom_fallback) isUnlocked isUnfreezed(_to) returns (bool success) { if(isContract(_to)) { if (balances[msg.sender] < _value) return false; balances[msg.sender] = safeSub( balances[msg.sender] , _value ); balances[...
0.4.18
/** * @param token is the token address to stake for * @return currentTerm is the current latest term * @return latestTerm is the potential latest term * @return totalRemainingRewards is the as-of remaining rewards * @return currentReward is the total rewards at the current term * @return nextTermRewards is...
function getTokenInfo(address token) external view override returns ( uint256 currentTerm, uint256 latestTerm, uint256 totalRemainingRewards, uint256 currentReward, uint256 nextTermRewards, uint128 currentS...
0.7.1
/** * @notice Returns _termInfo[token][term]. */
function getTermInfo(address token, uint256 term) external view override returns ( uint128 stakeAdd, uint128 stakeSum, uint256 rewardSum ) { TermInfo memory termInfo = _termInfo[token][term]; stakeAdd = termInfo.s...
0.7.1
/** * @return userTerm is the latest term the user has updated to * @return stakeAmount is the latest amount of staking from the user has updated to * @return nextAddedStakeAmount is the next amount of adding to stake from the user has updated to * @return currentReward is the latest reward getting by the user ...
function getAccountInfo(address token, address account) external view override returns ( uint256 userTerm, uint256 stakeAmount, uint128 nextAddedStakeAmount, uint256 currentReward, uint256 nextLatestTermUserRewards, ...
0.7.1
//Salviamo l'indirizzo del creatore del contratto per inviare gli ether ricevuti
function ChrisCoin(){ owner = msg.sender; balances[msg.sender] = CREATOR_TOKEN; start = now; end = now.add(LENGHT_BONUS); //fine periodo bonus end2 = end.add(LENGHT_BONUS2); //fine periodo bonus end3 = end2.add(LENGHT_BONUS3); //fine periodo bonus end4 = end3.add(LENGHT_BONUS4); //fine periodo bonu...
0.4.18
//Creazione dei token
function createTokens() payable{ require(msg.value >= 0); uint256 tokens = msg.value.mul(10 ** decimals); tokens = tokens.mul(RATE); tokens = tokens.div(10 ** 18); if (bonusAllowed) { if (now >= start && now < end) { tokens += tokens.mul(PERC_BONUS).div(100); } if (now >= end && no...
0.4.18
// ######## MINTING
function rarityIndexForNumber(uint256 number, uint8 traitType) internal view returns (bytes1) { uint16 lowerBound = 0; for (uint8 i = 0; i < rarities[traitType].length; i++) { uint16 upperBound = lowerBound + rarities[traitType][i]; if (number >= lowerBound && number < upperB...
0.8.0
//Invio dei token con delega
function transferFrom(address _from, address _to, uint256 _value) returns (bool success){ require(allowed[_from][msg.sender] >= _value && balances[msg.sender] >= _value && _value > 0); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allo...
0.4.18
//brucia tutti i token rimanenti
function burnAll() public { require(msg.sender == owner); address burner = msg.sender; uint256 total = balances[burner]; if (total > CREATOR_TOKEN_END) { total = total.sub(CREATOR_TOKEN_END); balances[burner] = balances[burner].sub(total); if (_totalSupply >= total){ _totalSupply = _total...
0.4.18
//brucia la quantita' _value di token
function burn(uint256 _value) public { require(msg.sender == owner); require(_value > 0); require(_value <= balances[msg.sender]); _value = _value.mul(10 ** decimals); address burner = msg.sender; uint t = balances[burner].sub(_value); require(t >= CREATOR_TOKEN_END); bal...
0.4.18
// Initializer
function init( address _summoner, address _DAI_ADDR, uint256 _withdrawLimit, uint256 _consensusThresholdPercentage ) public { require(! initialized, "Initialized"); require(_consensusThresholdPercentage <= PRECISION, "Consensus threshold > 1"); initialized = true; memberCount = 1; ...
0.5.16
/** Member management */
function addMembers( address[] memory _newMembers, uint256[] memory _tributes, address[] memory _members, bytes[] memory _signatures, uint256[] memory _salts ) public withConsensus( this.addMembers.selector, abi.encode(_newMembers, _tributes), _members, _signature...
0.5.16
/** Fund management */
function transferDAI( address[] memory _dests, uint256[] memory _amounts, address[] memory _members, bytes[] memory _signatures, uint256[] memory _salts ) public withConsensus( this.transferDAI.selector, abi.encode(_dests, _amounts), _members, _signatures, _...
0.5.16
/** Posting bounties */
function postBounty( string memory _dataIPFSHash, uint256 _deadline, uint256 _reward, address _standardBounties, uint256 _standardBountiesVersion, address[] memory _members, bytes[] memory _signatures, uint256[] memory _salts ) public withConsensus( this.postBounty.sele...
0.5.16
/** Working on bounties */
function performBountyAction( uint256 _bountyID, string memory _dataIPFSHash, address _standardBounties, uint256 _standardBountiesVersion, address[] memory _members, bytes[] memory _signatures, uint256[] memory _salts ) public withConsensus( this.performBountyAction.selecto...
0.5.16
/** Consensus */
function naiveMessageHash( bytes4 _funcSelector, bytes memory _funcParams, uint256 _salt ) public view returns (bytes32) { // "|END|" is used to separate _funcParams from the rest, to prevent maliciously ambiguous signatures return keccak256(abi.encodeWithSelector(_funcSelector, _funcPa...
0.5.16
// limits how much could be withdrawn each day, should be called before transfer() or approve()
function _applyWithdrawLimit(uint256 _amount) internal { // check if the limit will be exceeded if (_timestampToDayID(now).sub(_timestampToDayID(lastWithdrawTimestamp)) >= 1) { // new day, don't care about existing limit withdrawnToday = 0; } uint256 newWithdrawnToday = withdrawnToday.add(_a...
0.5.16
/// @dev In later version, require authorities consensus /// @notice Add an approved version of Melon /// @param ofVersion Address of the version to add /// @return id integer ID of the version (list index)
function addVersion( address ofVersion ) pre_cond(msg.sender == address(this)) returns (uint id) { require(msg.sender == address(this)); Version memory info; info.version = ofVersion; info.active = true; info.timestamp = now; ver...
0.4.21
/** * Based on http://www.codecodex.com/wiki/Calculate_an_integer_square_root */
function sqrt(uint num) internal returns (uint) { if (0 == num) { // Avoid zero divide return 0; } uint n = (num / 2) + 1; // Initial estimate, never low uint n1 = (n + (num / n)) / 2; while (n1 < n) { n = n1; n1 = (n + (num / n)) / 2; } retu...
0.4.11
/** * @dev Calculates how many tokens one can buy for specified value * @return Amount of tokens one will receive and purchase value without remainder. */
function getBuyPrice(uint _bidValue) constant returns (uint tokenCount, uint purchaseValue) { // Token price formula is twofold. We have flat pricing below tokenCreationMin, // and above that price linarly increases with supply. uint flatTokenCount; uint startSupply; u...
0.4.11
/** * @dev Calculates average token price for sale of specified token count * @return Total value received for given sale size. */
function getSellPrice(uint _askSizeTokens) constant returns (uint saleValue) { uint flatTokenCount; uint linearTokenMin; if(totalSupply <= tokenCreationMin) { return tokenPriceMin * _askSizeTokens; } if(totalSupply.sub(_askSizeTokens) < token...
0.4.11
/** * @dev Buy tokens with limit maximum average price * @param _maxPrice Maximum price user want to pay for one token */
function buyLimit(uint _maxPrice) payable public fundingActive { require(msg.value >= tokenPriceMin); assert(!isHalted); uint boughtTokens; uint averagePrice; uint purchaseValue; (boughtTokens, purchaseValue) = getBuyPrice(msg.value); if...
0.4.11
/** * @dev Sell tokens with limit on minimum average priceprice * @param _tokenCount Amount of tokens user wants to sell * @param _minPrice Minimum price user wants to receive for one token */
function sellLimit(uint _tokenCount, uint _minPrice) public fundingActive { require(_tokenCount > 0); assert(balances[msg.sender] >= _tokenCount); uint saleValue = getSellPrice(_tokenCount); uint averagePrice = saleValue.div(_tokenCount); assert(averagePrice >= t...
0.4.11
// Safe STARL transfer function to admin.
function accessSTARLTokens(uint256 _pid, address _to, uint256 _amount) public { require(msg.sender == adminaddr, "sender must be admin address"); require(totalSTARLStaked.sub(totalSTARLUsedForPurchase) >= _amount, "Amount must be less than staked STARL amount"); PoolInfo storage pool = poolIn...
0.6.12
// Wallet Of Owner
function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < o...
0.8.7
/// @notice fallback function. ensures that you still receive tokens if you just send money directly to the contract /// @dev fallback function. buys tokens with all sent ether *unless* ether is sent from partner address; if it is, then distributes ether as rewards to token holders
function() external payable { if ( msg.sender == partnerAddress_ ) { //convert money sent from partner contract into rewards for all token holders makeItRain(); } else { purchaseTokens( msg.sender, msg.value ); } }
0.5.12
/// @notice uses all of message sender's accumulated rewards to buy more tokens for the sender /// @dev emits event DoubleDown(msg.sender, rewards , newTokens) and event Transfer(address(0), playerAddress, newTokens) since function mint is called internally
function doubleDown() external { //pull current ether value of sender's rewards uint256 etherValue = rewardsOf( msg.sender ); //update rewards tracker to reflect payout. performed before rewards are sent to prevent re-entrancy updateSpentRewards( msg.sender , etherValue); //update slush f...
0.5.12
/// @notice converts all of message senders's accumulated rewards into cold, hard ether /// @dev emits event CashOut( msg.sender, etherValue ) /// @return etherValue sent to account holder
function cashOut() external returns (uint256 etherValue) { //pull current ether value of sender's rewards etherValue = rewardsOf( msg.sender ); //update rewards tracker to reflect payout. performed before rewards are sent to prevent re-entrancy updateSpentRewards( msg.sender , etherValue)...
0.5.12
/// @notice transfers tokens from sender to another address. Pays fee at same rate as buy/sell /// @dev emits event Transfer( msg.sender, toAddress, tokensAfterFee ) /// @param toAddress Destination for transferred tokens /// @param amountTokens The number of tokens the sender wants to transfer
function transfer( address toAddress, uint256 amountTokens ) external returns( bool ) { //make sure message sender has the requested tokens (transfers also disabled during SetupPhase) require( ( amountTokens <= tokenBalanceLedger_[ msg.sender ] && !setupPhase ), "transfer not allowed" ); //mak...
0.5.12
// PUBLIC FUNCTIONS
function whitelistMint(uint256 _numTokens) external payable { require(isAllowListActive, "Whitelist is not active."); require(_allowList[msg.sender] == true, "Not whitelisted."); require(_numTokens <= MAX_MINT_PER_TX, "You can only mint a maximum of 2 per transaction."); require(mint...
0.8.9
/** * Destroy tokens from other account */
function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balances[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowed[_from][msg.sender]); // Check allowance balances[_from] -= _value; ...
0.5.11
/// @notice increases approved amount of tokens that an external address can transfer on behalf of the user /// @dev emits event Approval(msg.sender, approvedAddress, newAllowance) /// @param approvedAddress External address to give approval to (i.e. to give control to transfer sender's tokens) /// @param amountTokens ...
function increaseAllowance( address approvedAddress, uint256 amountTokens) external returns (bool) { uint256 pastAllowance = allowance[msg.sender][approvedAddress]; uint256 newAllowance = SafeMath.add( pastAllowance , amountTokens ); allowance[msg.sender][approvedAddress] = newAllowance; ...
0.5.12
/// @notice transfers tokens from one address to another. Pays fee at same rate as buy/sell /// @dev emits event Transfer( fromAddress, toAddress, tokensAfterFee ) /// @param fromAddress Account that sender wishes to transfer tokens from /// @param toAddress Destination for transferred tokens /// @param amountTokens Th...
function transferFrom(address payable fromAddress, address payable toAddress, uint256 amountTokens) checkTransferApproved(fromAddress , amountTokens) external returns (bool) { // make sure sending address has requested tokens (transfers also disabled during SetupPhase) require( ( amountTokens ...
0.5.12