comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/// @notice returns current set of destination wallets for investor migration
function getInvestorMigrationWallets(address investor) public constant returns (address[] wallets, uint112[] amounts) { Destination[] storage destinations = _destinations[investor]; wallets = new address[](destinations.length); amounts = new uint112[](destinati...
0.4.25
/// @notice unlocks 'investor' tokens by making them withdrawable from paymentToken /// @dev expects number of neumarks that is due on investor's account to be approved for LockedAccount for transfer /// @dev there are 3 unlock modes depending on contract and investor state /// in 'AcceptingUnlocks' state Neumarks ...
function unlockInvestor(address investor) private { // use memory storage to obtain copy and be able to erase storage Account memory accountInMem = _accounts[investor]; // silently return on non-existing accounts if (accountInMem.balance == 0) { return; ...
0.4.25
/// @notice locks funds of investors for a period of time, called by migration /// @param investor funds owner /// @param amount amount of funds locked /// @param neumarks amount of neumarks that needs to be returned by investor to unlock funds /// @param unlockDate unlockDate of migrating account /// @dev used only by...
function lock(address investor, uint112 amount, uint112 neumarks, uint32 unlockDate) private acceptAgreement(investor) { require(amount > 0); Account storage account = _accounts[investor]; if (account.unlockDate == 0) { // this is new account - unlockDate a...
0.4.25
// calculates investor's and platform operator's neumarks from total reward
function calculateNeumarkDistribution(uint256 rewardNmk) public pure returns (uint256 platformNmk, uint256 investorNmk) { // round down - platform may get 1 wei less than investor platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE; // rewardNmk > platformNmk alwa...
0.4.25
// calculates token amount for a given commitment at a position of the curve // we require that equity token precision is 0
function calculateTokenAmount(uint256 /*totalEurUlps*/, uint256 committedEurUlps) public constant returns (uint256 tokenAmountInt) { // we may disregard totalEurUlps as curve is flat, round down when calculating tokens return committedEurUlps / calculatePriceFraction(10...
0.4.25
// calculate contribution of investor
function calculateContribution( address investor, uint256 totalContributedEurUlps, uint256 existingInvestorContributionEurUlps, uint256 newInvestorContributionEurUlps, bool applyWhitelistDiscounts ) public constant returns ( bool ...
0.4.25
/// @notice checks terms against platform terms, reverts on invalid
function requireValidTerms(PlatformTerms platformTerms) public constant returns (bool) { // apply constraints on retail fundraising if (ALLOW_RETAIL_INVESTORS) { // make sure transfers are disabled after offering for retail investors require(!E...
0.4.25
// @notice time induced state transitions, called before logic // @dev don't use `else if` and keep sorted by time and call `state()` // or else multiple transitions won't cascade properly.
function advanceTimedState() private { // if timed state machine was not run, the next state will never come if (_pastStateTransitionTimes[uint32(ETOState.Setup)] == 0) { return; } uint256 t = block.timestamp; if (_state == ETOState.Setup && t >=...
0.4.25
/// @notice executes transition state function
function transitionTo(ETOState newState) private { ETOState oldState = _state; ETOState effectiveNewState = mBeforeStateTransition(oldState, newState); // require(validTransition(oldState, effectiveNewState)); _state = effectiveNewState; // store deadline for...
0.4.25
//////////////////////// /// @dev sets timed state machine in motion
function setStartDate( ETOTerms etoTerms, IEquityToken equityToken, uint256 startDate ) external onlyCompany onlyWithAgreement withStateTransition() onlyState(ETOState.Setup) { require(etoTerms == ETO_TERMS); require(equ...
0.4.25
/// commit function happens via ERC223 callback that must happen from trusted payment token /// @dev data in case of LockedAccount contains investor address and investor is LockedAccount address
function tokenFallback(address wallet, uint256 amount, bytes data) public withStateTransition() onlyStates(ETOState.Whitelist, ETOState.Public) { uint256 equivEurUlps = amount; bool isEuroInvestment = msg.sender == address(EURO_TOKEN); bool isEtherInvestment = ...
0.4.25
// // Overrides internal interface //
function mAdavanceLogicState(ETOState oldState) internal constant returns (ETOState) { // add 1 to MIN_TICKET_TOKEN because it was produced by floor and check only MAX CAP // WHITELIST CAP will not induce state transition as fixed slots should be able to invest till the...
0.4.25
// a copy of PlatformTerms working on local storage
function calculateNeumarkDistribution(uint256 rewardNmk) private constant returns (uint256 platformNmk, uint256 investorNmk) { // round down - platform may get 1 wei less than investor platformNmk = rewardNmk / PLATFORM_NEUMARK_SHARE; // rewardNmk > platformNmk...
0.4.25
/// called on transition to ETOState.Claim
function onClaimTransition() private { // platform operator gets share of NEU uint256 rewardNmk = NEUMARK.balanceOf(this); (uint256 platformNmk,) = calculateNeumarkDistribution(rewardNmk); assert(NEUMARK.transfer(PLATFORM_WALLET, platformNmk, "")); // company l...
0.4.25
/// called on transtion to ETOState.Refund
function onRefundTransition() private { // burn all neumark generated in this ETO uint256 balanceNmk = NEUMARK.balanceOf(this); uint256 balanceTokenInt = EQUITY_TOKEN.balanceOf(this); if (balanceNmk > 0) { NEUMARK.burn(balanceNmk); } // de...
0.4.25
/// called on transition to ETOState.Payout
function onPayoutTransition() private { // distribute what's left in balances: company took funds on claim address disbursal = UNIVERSE.feeDisbursal(); assert(disbursal != address(0)); address platformPortfolio = UNIVERSE.platformPortfolio(); assert(platformPor...
0.4.25
/** * @dev Returns the seller that put a given NFT into escrow, * or bubbles the call up to check the current owner if the NFT is not currently in escrow. */
function _getSellerFor(address nftContract, uint256 tokenId) internal view virtual override returns (address payable) { address payable seller = auctionIdToAuction[ nftContractToTokenIdToAuctionId[nftContract][tokenId] ].seller; if (seller ...
0.8.4
/** * @notice Creates an auction for the given NFT. * The NFT is held in escrow until the auction is finalized or canceled. */
function createReserveAuction( address nftContract, uint256 tokenId, uint256 reservePrice ) public onlyValidAuctionConfig(reservePrice) nonReentrant notBanned(nftContract, tokenId) { // If an auction is already in progress then the NFT would be in ...
0.8.4
/** * @notice If an auction has been created but has not yet received bids, the configuration * such as the reservePrice may be changed by the seller. */
function updateReserveAuction(uint256 auctionId, uint256 reservePrice) public onlyValidAuctionConfig(reservePrice) { ReserveAuction storage auction = auctionIdToAuction[auctionId]; require( auction.seller == msg.sender, "NFTMarketReserveAuction: Not your aucti...
0.8.4
/** * @notice If an auction has been created but has not yet received bids, it may be canceled by the seller. * The NFT is returned to the seller from escrow. */
function cancelReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require( auction.seller == msg.sender, "NFTMarketReserveAuction: Not your auction" ); require( auction.endTime == 0, ...
0.8.4
/** * @notice Once the countdown has expired for an auction, anyone can settle the auction. * This will send the NFT to the highest bidder and distribute funds. */
function finalizeReserveAuction(uint256 auctionId) public nonReentrant { ReserveAuction memory auction = auctionIdToAuction[auctionId]; require( auction.endTime > 0, "NFTMarketReserveAuction: Auction was already settled" ); require( auction.endTime < b...
0.8.4
/** * @dev Determines the minimum bid amount when outbidding another user. */
function _getMinBidAmountForReserveAuction(uint256 currentBidAmount) private view returns (uint256) { uint256 minIncrement = currentBidAmount.mul( _minPercentIncrementInBasisPoints ) / BASIS_POINTS; if (minIncrement == 0) { // The next bid must...
0.8.4
/** * @notice Allows Blocksport to cancel an auction, refunding the bidder and returning the NFT to the seller. * This should only be used for extreme cases such as DMCA takedown requests. The reason should always be provided. */
function _adminCancelReserveAuction(uint256 auctionId, string memory reason) private onlyBlocksportAdmin { require( bytes(reason).length > 0, "NFTMarketReserveAuction: Include a reason for this cancellation" ); ReserveAuction memory auction = auctionId...
0.8.4
/** * @notice Allows Blocksport to ban token, refunding the bidder and returning the NFT to the seller. */
function adminBanToken( address nftContract, uint256 tokenId, string memory reason ) public onlyBlocksportAdmin { require( bytes(reason).length > 0, "NFTMarketReserveAuction: Include a reason for this ban" ); require(!bannedTokens[nftContract][...
0.8.4
/** * @notice Allows Blocksport to unban token, and list it again with no bids in the auction. */
function adminUnbanToken(address nftContract, uint256 tokenId) public onlyBlocksportAdmin { require( !bannedTokens[nftContract][tokenId], "NFTMarketReserveAuction: Token not banned" ); if (bannedAuction[nftContract][tokenId].tokenId > 0) { ...
0.8.4
/** * Begins the crowdsale (presale period) * @param tokenContractAddress - address of the `WIN` contract (token holder) * @dev must be called by one of owners */
function startPresale (address tokenContractAddress) onlyOneOfOwners { require(state == State.NotStarted); win = WIN(tokenContractAddress); assert(win.balanceOf(this) >= tokensForPeriod(0)); periods[0] = Period(now, NEVER, PRESALE_TOKEN_PRICE, 0); PeriodStarted(0,...
0.4.15
/** * Withdraws the money to be spent to Blind Croupier Project needs * @param amount - amount of Wei to withdraw (total) */
function withdraw (uint256 amount) onlyOneOfOwners { require(this.balance >= amount); uint totalShares = 0; for(var idx = 0; idx < owners.length; idx++) { totalShares += owners[idx].share; } for(idx = 0; idx < owners.length; idx++) { owners...
0.4.15
// function sliceBytes32To10(bytes32 input) public pure returns (bytes10 output) { // assembly { // output := input // } // }
function claim(address _to, uint256 _tokenId, string memory _tokenMidContent) public { require(_tokenId >= 0 && _tokenId < 2392, "Token ID invalid"); if (_tokenId >= 0 && _tokenId < 104) { require(bytes(_tokenMidContent).length == 429, "Token Content Size invalid"); require(_toke...
0.8.7
/// @dev not test for functions related to signature
function verifySignature( uint256[] memory _tokenIds, uint256 _price, address _paymentTokenAddress, bytes memory _signature ) internal view returns (bool) { bytes32 messageHash = getMessageHash( _tokenIds, _price, _paymentTokenAddress ...
0.8.7
// ----- PUBLIC METHODS ----- //
function buyToken( uint256[] memory _tokenIds, uint256 _price, address _paymentToken, address _receiver, bytes memory _signature ) external payable { require(_tokenIds.length == 1, "More than one token"); require( verifySignature(_tokenIds, _price,...
0.8.7
//called when transfers happened, to ensure new users will generate tokens too
function rewardSystemUpdate(address from, address to) external { require(msg.sender == address(PixelTigers)); if(from != address(0)){ storeRewards[from] += pendingReward(from); lastUpdate[from] = block.timestamp; } if(to != address(0)){ storeRewards[to...
0.8.4
// Register player
function playerRegister(string memory name, uint64[] memory numbers) payable public { require(contractActive == true, "Contract was disabled"); require(state == State.Accepting, "Game state is not valid"); require(numbers.length > 0, "At least 1 number"); require(msg.value >= minPrice * numbers.leng...
0.5.0
// Emergency drain in case of a bug // Adds all funds to owner to refund people // Designed to be as simple as possible
function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { require(contractStartTimestamp.add(8 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens (bool success, ) = msg.sender.call.value(address(this).bala...
0.6.12
// ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) { require(to != address(0)); require(tokens > 0); require(balances[msg.sender] >= tokens); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); ...
0.4.24
// Mint function for OG sale // Caller MUST be OG-Whitelisted to use this function!
function freeWhitelistMint() external isWallet enoughSupply(maxMintsOg) { require(freeWhitelistEnabled, 'OG sale not enabled'); if (isGenesis) { require(genesisOg[msg.sender] >= maxMintsOg, 'Not a wiggle world OG'); genesisOg[msg.sender] = genesisOg[msg.sender] - maxMintsOg; ...
0.8.4
// Mint function for whitelist sale // Requires minimum ETH value of unitPrice * quantity // Caller MUST be whitelisted to use this function!
function paidWhitelistMint(uint256 quantity) external payable isWallet enoughSupply(quantity) { require(paidWhitelistEnabled, 'Whitelist sale not enabled'); require(msg.value >= quantity * unitPrice, 'Not enough ETH'); if (isGenesis) { require(genesisWhitelist[msg.sender] >= quantity...
0.8.4
// Mint function for public sale // Requires minimum ETH value of unitPrice * quantity
function publicMint(uint256 quantity) external payable isWallet enoughSupply(quantity) { require(publicMintEnabled, 'Minting not enabled'); require(quantity <= maxMints, 'Illegal quantity'); require(numberMinted(msg.sender) + quantity <= maxMints, 'Cant mint that many'); require(msg.valu...
0.8.4
// Mint function for developers (owner) // Mints a maximum of 20 NFTs to the recipient // Used for devs, marketing, friends, family // Capped at 55 mints total
function devMint(uint256 quantity, address recipient) external onlyOwner enoughSupply(quantity) { if (isGenesis) { require(remainingDevSupply - quantity >= genesisDevCutoff, 'No dev supply (genesis)'); } else { require(remainingDevSupply - quantity >= ...
0.8.4
// Returns the correct URI for the given tokenId based on contract state
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), 'Nonexistent token'); if ( (tokenId < genesisCollectionSize && genesisRevealed == false) || (tokenId >= genesisCollectionSize && revealed == false) ) { ...
0.8.4
// Update relevant mint format variables. // Should only be called once, // To change price between genesis and second mint.
function updateMintFormat( uint256 _ogSlots, uint256 _ogWlSlots, uint256 _wlSlots, uint256 _maxMints, uint256 _numBackgrounds ) external onlyOwner { maxMintsOg = _ogSlots; ogWlMints = _ogWlSlots; maxMintsWhitelist = _wlSlots; maxMints = _maxMin...
0.8.4
// Set the mint state
function setMintState(uint256 _state) external onlyOwner { if (_state == 1) { freeWhitelistEnabled = true; } else if (_state == 2) { paidWhitelistEnabled = true; } else if (_state == 3) { publicMintEnabled = true; } else { freeWhitelistEnab...
0.8.4
// Seed the appropriate whitelist
function setWhitelist(address[] calldata addrs, bool isOG) external onlyOwner { if (isOG) { for (uint256 i = 0; i < addrs.length; i++) { if (isGenesis) { genesisOg[addrs[i]] = maxMintsOg; genesisWhitelist[addrs[i]] = ogWlMints; ...
0.8.4
/* Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. param _spender The address which will spend the funds. param _value The amount of Roman Lanskoj's tokens to be spent. */
function approve(address _spender, uint256 _value) returns (bool) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethe...
0.4.19
/** * @notice Transfer `_amount` from `_caller` to `_to`. * * @param _caller Origin address * @param _to Address that will receive. * @param _amount Amount to be transferred. */
function transfer(address _caller, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); assert(balanceOf[_caller] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to]); activateAccount(_caller); activateAccou...
0.3.6
/// @notice Calculate atomic number for a given tokenId and token hash /// @dev The reason it needs both is that atomic number is partially based on tokenId. /// @param _tokenId The tokenId of the Atom /// @param _hash Hash of Atom /// @return Atomic number of the given Atom
function calculateAtomicNumber(uint _tokenId, bytes32 _hash, uint generation) private pure returns(uint){ if(_tokenId == 1) return 0; bytes32 divisor = 0x0000000001000000000000000000000000000000000000000000000000000000; uint salt = uint(_hash)/uint(divisor); uint max; if...
0.8.4
/** * @notice Transfer `_amount` from `_from` to `_to`, invoked by `_caller`. * * @param _caller Invoker of the call (owner of the allowance) * @param _from Origin address * @param _to Address that will receive * @param _amount Amount to be transferred. * @return result of the method call */
function transferFrom(address _caller, address _from, address _to, uint256 _amount) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); assert(!frozenAccount[_from]); assert(balanceOf[_from] >= _amount); assert(balanceOf[_to] + _amount >= balanceOf[_to...
0.3.6
/** * @dev Moves tokens `_amount` from `_sender` to `_recipient`. * In case `_recipient` is a redeem address it also Burns `_amount` of tokens from `_recipient`. * * Emits a {Transfer} event. * * Requirements: * * - {userRegistry.canTransferFrom} should not revert */
function transferFrom( address _sender, address _recipient, uint256 _amount ) public override returns (bool) { userRegistry.canTransferFrom(_msgSender(), _sender, _recipient); super.transferFrom(_sender, _recipient, _amount); if (userRegistry.isRedeemFrom(_msgSender...
0.6.10
/** * @notice Approve Approves spender `_spender` to transfer `_amount` from `_caller` * * @param _caller Address that grants the allowance * @param _spender Address that receives the cheque * @param _amount Amount on the cheque * @param _extraData Consequential contract to be executed by spender in same tr...
function approveAndCall(address _caller, address _spender, uint256 _amount, bytes _extraData) onlyAsset returns (bool success) { assert(allowTransactions); assert(!frozenAccount[_caller]); allowance[_caller][_spender] = _amount; activateAccount(_caller); activateAccount(_spender); activate...
0.3.6
// get minimal proxy creation code
function minimalProxyCreationCode(address logic) internal pure returns (bytes memory) { bytes10 creation = 0x3d602d80600a3d3981f3; bytes10 prefix = 0x363d3d373d3d3d363d73; bytes20 targetBytes = bytes20(logic); bytes15 suffix = 0x5af43d82803e903d91602b57fd5bf3; return abi.enc...
0.7.3
// Allow the owner to easily create the default dice games
function createDefaultGames() public { require(allGames.length == 0); addNewStakeDiceGame(500); // 5% chance addNewStakeDiceGame(1000); // 10% chance addNewStakeDiceGame(1500); // 15% chance addNewStakeDiceGame(2000); // 20% chance addNewStakeDiceGame...
0.4.24
// Allow the owner to add new games with different winning chances
function addNewStakeDiceGame(uint256 _winningChance) public { require(msg.sender == owner); // Deploy a new StakeDiceGame contract StakeDiceGame newGame = new StakeDiceGame(this, _winningChance); // Store the fact that this new address is a StakeDiceGame cont...
0.4.24
/* * @dev Buy tokens from incoming funds */
function buy(address referrer) public payable { // apply fee (uint fee_funds, uint taxed_funds) = fee_purchase.split(msg.value); require(fee_funds != 0, "Incoming funds is too small"); // update user's referrer // - you cannot be a referrer for yourself // - u...
0.4.25
/* * @dev Sell given amount of tokens and get funds */
function sell(uint tokens) public onlyValidTokenAmount(tokens) { // calculate amount of funds and change price (uint funds, uint _price) = tokensToFunds(tokens); require(funds != 0, "Insufficient tokens to do that"); price = _price; // apply fee (uint fee_funds,...
0.4.25
/* * @dev Transfer given amount of tokens from sender to another user * ERC20 */
function transfer(address to_addr, uint tokens) public onlyValidTokenAmount(tokens) returns (bool success) { require(to_addr != msg.sender, "You cannot transfer tokens to yourself"); // apply fee (uint fee_tokens, uint taxed_tokens) = fee_transfer.split(tokens); require(fee_token...
0.4.25
/* * @dev Reinvest all dividends */
function reinvest() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user....
0.4.25
/* * @dev Withdraw all dividends */
function withdraw() public { // get all dividends uint funds = dividendsOf(msg.sender); require(funds > 0, "You have no dividends"); // make correction, dividents will be 0 after that UserRecord storage user = user_data[msg.sender]; user.funds_correction = user....
0.4.25
/* * @dev Amount of user's dividends */
function dividendsOf(address addr) public view returns (uint) { UserRecord memory user = user_data[addr]; // gained funds from selling tokens + bonus funds from referrals // int because "user.funds_correction" can be negative int d = int(user.gained_funds.add(user.ref_funds)); ...
0.4.25
/* * @dev Amount of tokens can be gained from given amount of funds */
function expectedTokens(uint funds, bool apply_fee) public view returns (uint) { if (funds == 0) { return 0; } if (apply_fee) { (,uint _funds) = fee_purchase.split(funds); funds = _funds; } (uint tokens,) = fundsToTokens(funds); ...
0.4.25
/* * @dev Mint given amount of tokens to given user */
function mintTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; bool not_first_minting = total_supply > 0; // make correction to keep dividends the rest of the users if (not_first_minting) { shared_profit = shared_profit.mul(tot...
0.4.25
/* * @dev Burn given amout of tokens from given user */
function burnTokens(address addr, uint tokens) internal { UserRecord storage user = user_data[addr]; // keep current dividents of user if last tokens will be burned uint dividends_from_tokens = 0; if (total_supply == tokens) { dividends_from_tokens = shared_profit.mu...
0.4.25
/* * @dev Rewards the referrer from given amount of funds */
function rewardReferrer(address addr, address referrer_addr, uint funds, uint full_funds) internal returns (uint funds_after_reward) { UserRecord storage referrer = user_data[referrer_addr]; if (referrer.tokens >= minimal_stake) { (uint reward_funds, uint taxed_funds) = fee_referral.split...
0.4.25
/* * @dev Calculate tokens from funds * * Given: * a[1] = price * d = price_offset * sum(n) = funds * Here is used arithmetic progression's equation transformed to a quadratic equation: * a * n^2 + b * n + c = 0 * Where: * a = d * b = 2 * a[1] - d * c = -2 * sum(n) * Solve it and...
function fundsToTokens(uint funds) internal view returns (uint tokens, uint _price) { uint b = price.mul(2).sub(price_offset); uint D = b.mul(b).add(price_offset.mul(8).mul(funds).mul(precision_factor)); uint n = D.sqrt().sub(b).mul(precision_factor) / price_offset.mul(2); uint anp1 ...
0.4.25
/* * @dev Calculate funds from tokens * * Given: * a[1] = sell_price * d = price_offset * n = tokens * Here is used arithmetic progression's equation (-d because of d must be negative to reduce price): * a[n] = a[1] - d * (n - 1) * sum(n) = (a[1] + a[n]) * n / 2 * So: * funds = sum(n) ...
function tokensToFunds(uint tokens) internal view returns (uint funds, uint _price) { uint sell_price = price.sub(price_offset); uint an = sell_price.add(price_offset).sub(price_offset.mul(tokens) / precision_factor); uint sn = sell_price.add(an).mul(tokens) / precision_factor.mul(2); ...
0.4.25
/** * @dev Multiplies two numbers */
function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "mul failed"); return c; }
0.4.25
/** * @dev Gives square root from number */
function sqrt(uint x) internal pure returns (uint y) { uint z = add(x, 1) / 2; y = x; while (z < y) { y = z; z = add(x / z, z) / 2; } }
0.4.25
/* * @dev Splits given value to two parts: tax itself and taxed value */
function split(fee memory f, uint value) internal pure returns (uint tax, uint taxed_value) { if (value == 0) { return (0, 0); } tax = value.mul(f.num) / f.den; taxed_value = value.sub(tax); }
0.4.25
/* Gets 1-f^t where: f < 1 f: issuance factor that determines the shape of the curve t: time passed since last LQTY issuance event */
function _getCumulativeIssuanceFraction() internal view returns (uint) { // Get the time passed since deployment uint timePassedInMinutes = block.timestamp.sub(deploymentTime).div(SECONDS_IN_ONE_MINUTE); // f^t uint power = LiquityMath._decPow(ISSUANCE_FACTOR, timePassedInMinutes); ...
0.6.11
/// @notice Used by Certifying Authorities to change their wallet (in case of theft). /// Migrating prevents any new certificate registrations signed by the old wallet. /// Already registered certificates would be valid. /// @param _newAuthorityAddress Next wallet address of the same certifying authority
function migrateCertifyingAuthority( address _newAuthorityAddress ) public onlyAuthorisedCertifier { require( certifyingAuthorities[_newAuthorityAddress].status == AuthorityStatus.NotAuthorised , 'cannot migrate to an already authorised address' ); certifyingAuthorities[msg.sender].status...
0.6.2
/// @notice Used to check whether an address exists in packed addresses bytes /// @param _signer Address of the signer wallet /// @param _packedSigners Bytes string of addressed packed together /// @return boolean value which means if _signer doesnot exist in _packedSigners bytes string
function _checkUniqueSigner( address _signer, bytes memory _packedSigners ) private pure returns (bool){ if(_packedSigners.length == 0) return true; require(_packedSigners.length % 20 == 0, 'invalid packed signers length'); address _tempSigner; /// @notice loop through every packed signer an...
0.6.2
/// @notice Used to get a number's utf8 representation /// @param i Integer /// @return utf8 representation of i
function _getBytesStr(uint i) private pure returns (bytes memory) { if (i == 0) { return "0"; } uint j = i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10))...
0.6.2
/* Send coins from the caller's account */
function transfer(address _to, uint256 _value) public { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overfl...
0.4.8
/* Send coins from an account that previously approved this caller to do so */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { if (_to == 0x0) throw; // Prevent transfer to 0x0 address. Use burn() instead if (_value <= 0) throw; if (balanceOf[_from] < _value) throw; // Check if the sender has enough if (balanceOf[_to] + _value < balan...
0.4.8
/* Permanently delete some number of coins that are in the caller's account */
function burn(uint256 _value) public returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender totalSupply = SafeMath.safeSub(totalSupply,_...
0.4.8
/* Make some of the caller's coins temporarily unavailable */
function freeze(uint256 _value) public returns (bool success) { if (balanceOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; balanceOf[msg.sender] = SafeMath.safeSub(balanceOf[msg.sender], _value); // Subtract from the sender freezeOf[msg.sender] = SafeMath.safeAdd(fr...
0.4.8
/* Frozen coins can be made available again by unfreezing them */
function unfreeze(uint256 _value) public returns (bool success) { if (freezeOf[msg.sender] < _value) throw; // Check if the sender has enough if (_value <= 0) throw; freezeOf[msg.sender] = SafeMath.safeSub(freezeOf[msg.sender], _value); // Subtract from sender's frozen balance balanceOf[msg.sender] = SafeMa...
0.4.8
/* Attempt to purchase the tokens from the token contract. This must be done before the sale ends */
function buyTokens() external onlyWhenRefundsNotEnabled onlyWhenTokensNotPurchased onlyOwner { require(this.balance >= totalPresale); tokenContract.buyTokens.value(this.balance)(); //Get the exchange rate the contract will got for the purchase. Used to distribute tokens //The numbe...
0.4.18
/* Transfer an accounts token entitlement to itself. This can only be called if the tokens have been purchased by the contract and have been withdrawn by the contract. */
function withdrawTokens() external onlyWhenSyndicateTokensWithdrawn { uint256 tokens = SafeMath.div(SafeMath.mul(presaleBalances[msg.sender], tokenExchangeRate), 1 ether); assert(tokens > 0); totalPresale = SafeMath.sub(totalPresale, presaleBalances[msg.sender]); presaleBalances[ms...
0.4.18
// Burn FRIES from account with approval
function burnFrom(address account, uint256 amount) external { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); ...
0.8.7
/* * @param item RLP encoded list in bytes */
function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items = numItems(item); RLPItem[] memory result = new RLPItem[](items); uint memPtr = item.memPtr + _payloadOffset(item.memPtr); uint dataLen; for (uint i = 0; i < items; i++) { da...
0.6.2
// @return indicator whether encoded payload is a list. negate this function call for isData.
function isList(RLPItem memory item) internal pure returns (bool) { if(item.len == 0) return false; uint8 byte0; uint memPtr = item.memPtr; assembly { byte0 := byte(0, mload(memPtr)) } if(byte0 < LIST_SHORT_START) return false; return true; }
0.6.2
// @returns raw rlp encoding in bytes
function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; }
0.6.2
// any non-zero byte is considered true
function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr = item.memPtr; assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; }
0.6.2
// enforces 32 byte length
function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr = item.memPtr + 1; assembly { result := mload(memPtr) } return result; }
0.6.2
// @return number of payload items inside an encoded list.
function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count = 0; uint currPtr = item.memPtr + _payloadOffset(item.memPtr); uint endPtr = item.memPtr + item.len; while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over a...
0.6.2
// @return entire rlp item byte length
function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte...
0.6.2
// @return number of bytes until the data
function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if...
0.6.2
/* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */
function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. ...
0.6.2
/** * Finalize a succcesful crowdsale. * * The owner can triggre a call the contract that provides post-crowdsale actions, like releasing the tokens. */
function finalize() public inState(State.Success) onlyOwner stopInEmergency { // Already finalized if(finalized) { throw; } // Finalizing is optional. We only call it if we are given a finalizing agent. if(address(finalizeAgent) != 0) { finalizeAgent.finalizeCrowdsale(); ...
0.4.8
/** * Crowdfund state machine management. * * We make it a function and do not assign the result to a variable, so there is no chance of the variable being stale. */
function getState() public constant returns (State) { if(finalized) return State.Finalized; else if (address(finalizeAgent) == 0) return State.Preparing; else if (!finalizeAgent.isSane()) return State.Preparing; else if (!pricingStrategy.isSane(address(this))) return State.Preparing; else if (b...
0.4.8
/** * Set the contract that can call release and make the token transferable. * * Design choice. Allow reset the release agent to fix fat finger mistakes. */
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public { // We don't do interface check here as we might want to a normal wallet address to act as a release agent releaseAgent = addr; }
0.4.8
/** * Calculate the current price for buy in amount. * * @param {uint amount} How many tokens we get */
function calculatePrice(uint value, uint weiRaised, uint tokensSold, address msgSender, uint decimals) public constant returns (uint) { uint multiplier = 10 ** decimals; if (weiRaised > getSoftCapInWeis()) { //Here SoftCap is not active yet return value.times(multiplier) / convertToWei(hardCap...
0.4.8
/** * Post crowdsale distribution process. * * Exposed as public to make it testable. */
function distribute(uint amount_raised_chf, uint eth_chf_price) { // Only crowdsale contract or owner (manually) can trigger the distribution if(!(msg.sender == address(crowdsale) || msg.sender == owner)) { throw; } // Distribute: // seed coins // foundation coins // team c...
0.4.8
/// @dev Here you can set all the Vaults
function setVaults( address _futureRoundVault, address _foundationWallet, address _teamVault, address _seedVault1, address _seedVault2 ) onlyOwner { futureRoundVault = _futureRoundVault; foundationWallet = _foundationWallet; teamVault = _teamVault; seedVault1 = _seedVault...
0.4.8
/** * @notice Transfer `amount` USDC from `msg.sender` to this contract, use them * to mint cUSDC, and mint dTokens with `msg.sender` as the beneficiary. Ensure * that this contract has been approved to transfer the USDC on behalf of the * caller. * @param usdcToSupply uint256 The amount of usdc to provide as...
function mint( uint256 usdcToSupply ) external accrues returns (uint256 dUSDCMinted) { // Determine the dUSDC to mint using the exchange rate dUSDCMinted = usdcToSupply.mul(_SCALING_FACTOR).div(_dUSDCExchangeRate); // Pull in USDC (requires that this contract has sufficient allowance) requ...
0.5.11
/** * @notice Redeem `dUSDCToBurn` dUSDC from `msg.sender`, use the corresponding * cUSDC to redeem USDC, and transfer the USDC to `msg.sender`. * @param dUSDCToBurn uint256 The amount of dUSDC to provide for USDC. * @return The amount of usdc received in return for the provided cUSDC. */
function redeem( uint256 dUSDCToBurn ) external accrues returns (uint256 usdcReceived) { // Determine the underlying USDC value of the dUSDC to be burned usdcReceived = dUSDCToBurn.mul(_dUSDCExchangeRate) / _SCALING_FACTOR; // Burn the dUSDC _burn(msg.sender, usdcReceived, dUSDCToBurn); ...
0.5.11
/** * @notice Redeem the dUSDC equivalent value of USDC amount `usdcToReceive` from * `msg.sender`, use the corresponding cUSDC to redeem USDC, and transfer the * USDC to `msg.sender`. * @param usdcToReceive uint256 The amount, denominated in USDC, of the cUSDC to * provide for USDC. * @return The amount of...
function redeemUnderlying( uint256 usdcToReceive ) external accrues returns (uint256 dUSDCBurned) { // Determine the dUSDC to redeem using the exchange rate dUSDCBurned = usdcToReceive.mul(_SCALING_FACTOR).div(_dUSDCExchangeRate); // Burn the dUSDC _burn(msg.sender, usdcToReceive, dUSDCBur...
0.5.11
/** * @notice Transfer cUSDC in excess of the total dUSDC balance to a dedicated * "vault" account. * @return The amount of cUSDC transferred to the vault account. */
function pullSurplus() external accrues returns (uint256 cUSDCSurplus) { // Determine the cUSDC surplus (difference between total dUSDC and total cUSDC) cUSDCSurplus = _getSurplus(); // Send the cUSDC surplus to the vault require(_CUSDC.transfer(_VAULT, cUSDCSurplus), "cUSDC transfer failed."); ...
0.5.11
/** * @notice Transfer `amount` tokens from `sender` to `recipient` as long as * `msg.sender` has sufficient allowance. * @param sender address The account to transfer tokens from. * @param recipient address The account to transfer tokens to. * @param amount uint256 The amount of tokens to transfer. * @retu...
function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(sender, recipient, amount); uint256 allowance = _allowances[sender][msg.sender]; if (allowance != uint256(-1)) { _approve(sender, msg.sender, allowance.sub(amount)); } r...
0.5.11
/** * @notice View function to get the dUSDC balance of an account, denominated in * its USDC equivalent value. * @param account address The account to check the balance for. * @return The total USDC-equivalent cUSDC balance. */
function balanceOfUnderlying( address account ) external returns (uint256 usdcBalance) { // Get most recent dUSDC exchange rate by determining accrued interest (uint256 dUSDCExchangeRate,,) = _getAccruedInterest(); // Convert account balance to USDC equivalent using the exchange rate usdcB...
0.5.11
/** * @notice Internal function to burn `amount` tokens by exchanging `exchanged` * tokens from `account` and emit corresponding `Redeeem` & `Transfer` events. * @param account address The account to burn tokens from. * @param exchanged uint256 The amount of underlying tokens given for burning. * @param amoun...
function _burn(address account, uint256 exchanged, uint256 amount) internal { uint256 balancePriorToBurn = _balances[account]; require( balancePriorToBurn >= amount, "Supplied amount exceeds account balance." ); _totalSupply = _totalSupply.sub(amount); _balances[account] = balancePrior...
0.5.11