comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @notice Returns the target ratio if reserveA and reserveB are 0 (for initial deposit) * currentRatio := (reserveA denominated in tokenB / reserveB denominated in tokenB) with decI decimals */
function currentRatio( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { if (t.reserveA == 0 || t.reserveB == 0) { if (t.reserveA == 0 && t.reserveB == 0) return t.targetRatio; if (t.reserveA =...
0.8.1
/** * @notice Returns the deviation of reserveA and reserveB from target ratio * currentRatio > targetRatio: release TokenA liquidity and add TokenB liquidity * currentRatio < targetRatio: add TokenA liquidity and release TokenB liquidity * deltaA := abs(t.reserveA, (t.reserveB / rate * t.targetRatio)) / (1 + t.tar...
function trancheDelta( IEPool.Tranche memory t, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange) { rChange = (currentRatio(t, rate, sFactorA, sFactorB) < t.targetRatio) ? 1 : 0; deltaA = ( ...
0.8.1
/** * @notice Returns the sum of the tranches reserve deltas */
function delta( IEPool.Tranche[] memory ts, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 deltaA, uint256 deltaB, uint256 rChange, uint256 rDiv) { uint256 totalReserveA; int256 totalDeltaA; int256 totalDeltaB; for (u...
0.8.1
/** * @dev Set geneSequences of assets available * @dev Used as 1 of 1s or 1 of Ns (N being same geneSequence repeated N times) */
function setAssets(uint16[] memory _assets) public onlyOwner { uint256 maxSupply = lobsterBeachClub.maxSupply(); require(_assets.length <= maxSupply, "You cannot supply more assets than max supply"); for (uint i; i < _assets.length; i++) { require(_assets[i] > 0 && _assets[i] < 1000,...
0.8.7
/** * @notice how much EToken can be issued, redeemed for amountA and amountB * initial issuance / last redemption: sqrt(amountA * amountB) * subsequent issuances / non nullifying redemptions: claim on reserve * EToken total supply */
function eTokenForTokenATokenB( IEPool.Tranche memory t, uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal view returns (uint256) { uint256 amountsA = totalA(amountA, amountB, rate, sFactorA, sFactorB); if (t...
0.8.1
/** * Utility internal function used to safely transfer `value` tokens `from` -> `to`. Throws if transfer is impossible. * @param from - account to make the transfer from * @param to - account to transfer `value` tokens to * @param value - tokens to transfer to account `to` */
function internalTransfer (address from, address to, uint value) internal { require(to != address(0x0)); // Prevent people from accidentally burning their tokens balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); ...
0.7.0
/** * Utility internal function used to safely transfer `value1` tokens `from` -> `to1`, and `value2` tokens * `from` -> `to2`, minimizing gas usage (calling `internalTransfer` twice is more expensive). Throws if * transfers are impossible. * @param from - account to make the transfer from * @param to1 - acco...
function internalDoubleTransfer (address from, address to1, uint value1, address to2, uint value2) internal { require(to1 != address(0x0) && to2 != address(0x0)); // Prevent people from accidentally burning their tokens balanceOf[from] = balanceOf[from].sub(value1.add(value2)); balanceOf[to1]...
0.7.0
/** * Utility costly function to encode bytes HEX representation as string. * @param sig - signature as bytes32 to represent as string */
function hexToString (bytes32 sig) internal pure returns (bytes memory) { bytes memory str = new bytes(64); for (uint8 i = 0; i < 32; ++i) { str[2 * i] = byte((uint8(sig[i]) / 16 < 10 ? 48 : 87) + uint8(sig[i]) / 16); str[2 * i + 1] = byte((uint8(sig[i]) % 16 < 10 ? 48 : 87) ...
0.7.0
/** * This function distincts transaction signer from transaction executor. It allows anyone to transfer tokens * from the `from` account by providing a valid signature, which can only be obtained from the `from` account * owner. * Note that passed parameter sigId is unique and cannot be passed twice (prevents ...
function transferViaSignature ( address from, address to, uint256 value, uint256 fee, address feeRecipient, uint256 deadline, ...
0.7.0
/** * Same as `transferViaSignature`, but for `approve`. * Use case: the user wants to set an allowance for the smart contract or another user without having Ether on * their balance. * @param from - the account to approve withdrawal from, which signed all below parameters * @param spender - the account allow...
function approveViaSignature ( address from, address spender, uint256 value, uint256 fee, address feeRecipient, uint256 deadline, uint256 sigId, bytes calldata sig, sigStandard sigStd ...
0.7.0
/** * Same as `transferViaSignature`, but for `transferFrom`. * Use case: the user wants to withdraw tokens from a smart contract or another user who allowed the user to * do so. Important note: the fee is subtracted from the `value`, and `to` address receives `value - fee`. * @param signer - the address allowe...
function transferFromViaSignature ( address signer, address from, address to, uint256 value, uint256 fee, address feeRecipient, uint256 deadline, uint256 sigId, bytes calldata sig, ...
0.7.0
/** * Same as `approveViaSignature`, but for `approveAndCall`. * Use case: the user wants to send tokens to the smart contract and pass additional data within one transaction. * @param fromAddress - the account to approve withdrawal from, which signed all below parameters * @param spender - the account allowed ...
function approveAndCallViaSignature ( address fromAddress, address spender, uint256 value, bytes calldata extraData, uint256 fee, address feeRecipient, uint256 deadline, uint256 sigId, bytes...
0.7.0
/** * @dev Deterministically decides which tokenIds of maxSupply from lobsterBeachClub will receive each asset * @dev Determination is based on seedNumber * @dev To prevent from tokenHolders knowing which section of tokenIds are more likely to receive an asset * the direction which assets are chosen from 0 or ...
function getAssetOwned(uint256 tokenId) public view returns (uint16 assetId) { uint256 maxSupply = lobsterBeachClub.maxSupply(); uint256 seedNumber = lobsterBeachClub.seedNumber(); uint256 totalDistance = maxSupply; uint256 direction = seedNumber % 2; for (uint i; i < assets.leng...
0.8.7
/** * @notice Given amountA, which amountB is required such that amountB / amountA is equal to the ratio * amountB := amountAInTokenB / ratio */
function tokenBForTokenA( uint256 amountA, uint256 ratio, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns(uint256) { return (((amountA * sFactorI / sFactorA) * rate) / ratio) * sFactorB / sFactorI; }
0.8.1
/** * @dev Constructor that gives msg.sender all of existing tokens. */
function PSIToken() public { totalSupply = INITIAL_SUPPLY; //Round A Investors 15% balances[0xa801fcD3CDf65206F567645A3E8c4537739334A2] = 150000000 * (10 ** uint256(decimals)); emit Transfer(msg.sender, 0xa801fcD3CDf65206F567645A3E8c4537739334A2, 150000000 * (10 ** uint256(decimals))); ...
0.4.25
/** * @notice Return the total value of amountA and amountB denominated in TokenA * totalA := amountA + (amountB / rate) */
function totalA( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalA) { return amountA + ((((amountB * sFactorI / sFactorB) * sFactorI) / rate) * sFactorA) / sFactorI; }
0.8.1
/** * @notice Return the total value of amountA and amountB denominated in TokenB * totalB := amountB + (amountA * rate) */
function totalB( uint256 amountA, uint256 amountB, uint256 rate, uint256 sFactorA, uint256 sFactorB ) internal pure returns (uint256 _totalB) { return amountB + ((amountA * rate / sFactorA) * sFactorB) / sFactorI; }
0.8.1
/** * @notice Return the withdrawal fee for a given amount of TokenA and TokenB * feeA := amountA * feeRate * feeB := amountB * feeRate */
function feeAFeeBForTokenATokenB( uint256 amountA, uint256 amountB, uint256 feeRate ) internal pure returns (uint256 feeA, uint256 feeB) { feeA = amountA * feeRate / EPoolLibrary.sFactorI; feeB = amountB * feeRate / EPoolLibrary.sFactorI; }
0.8.1
/** * @param oToken opyn put option * @param _oTokenPayment USDC required for purchasing oTokens * @param _maxPayment in ETH for purchasing USDC; caps slippage * @param _0xFee 0x protocol fee. Any extra is refunded * @param _0xSwapData 0x swap encoded data */
function _mint( address oToken, uint _opeth, uint _oTokenPayment, uint _maxPayment, uint _0xFee, bytes calldata _0xSwapData ) internal { // Swap ETH for USDC (for purchasing oToken) Uni(uni).swapETHForExactTokens{value: _maxPayment}( _oToke...
0.6.12
/** * @dev Claims/mints an NFT token if the sender is eligible to claim via the merkle proof. */
function claim(bytes32[] memory proof) external { require(_root != 0, 'merkle root not set'); bytes32 leaf = keccak256(abi.encodePacked(msg.sender)); require(verify(proof, _root, leaf), 'sender not eligible to claim'); require(!_claimed[msg.sender], 'already claimed'); _claimed...
0.8.7
// msg.value = amountETH + oracle fee
function addLiquidity( address token, uint amountETH, uint amountToken, uint liquidityMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint liquidity) { // create the pair if it doesn't exist yet if (ICoFiXFactor...
0.6.12
// msg.value = oracle fee
function removeLiquidityGetToken( address token, uint liquidity, uint amountTokenMin, address to, uint deadline ) external override payable ensure(deadline) returns (uint amountToken) { require(msg.value > 0, "CRouter: insufficient msg.value"); address pai...
0.6.12
// msg.value = amountIn + oracle fee
function swapExactETHForTokens( address token, uint amountIn, uint amountOutMin, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > amountIn, "CRouter: in...
0.6.12
// msg.value = amountInMax + oracle fee
function swapETHForExactTokens( address token, uint amountInMax, uint amountOutExact, address to, address rewardTo, uint deadline ) external override payable ensure(deadline) returns (uint _amountIn, uint _amountOut) { require(msg.value > amountInMax, "CRo...
0.6.12
/** * @dev Returns an ordered pair (amountIn, amountOut) given the 'given' and 'calculated' amounts, and the swap kind. */
function _getAmounts( SwapKind kind, uint256 amountGiven, uint256 amountCalculated ) private pure returns (uint256 amountIn, uint256 amountOut) { if (kind == SwapKind.GIVEN_IN) { (amountIn, amountOut) = (amountGiven, amountCalculated); } else { // Swap...
0.7.1
/** * @dev Performs a swap according to the parameters specified in `request`, calling the Pool's contract hook and * updating the Pool's balance. * * Returns the amount of tokens going into or out of the Vault as a result of this swap, depending on the swap kind. */
function _swapWithPool(IPoolSwapStructs.SwapRequest memory request) private returns ( uint256 amountCalculated, uint256 amountIn, uint256 amountOut ) { // Get the calculated amount from the Pool and update its balances address pool = _getPo...
0.7.1
/** * @dev Calls the onSwap hook for a Pool that implements IMinimalSwapInfoPool: both Minimal Swap Info and Two Token * Pools do this. */
function _callMinimalSwapInfoPoolOnSwapHook( IPoolSwapStructs.SwapRequest memory request, IMinimalSwapInfoPool pool, bytes32 tokenInBalance, bytes32 tokenOutBalance ) internal returns ( bytes32 newTokenInBalance, bytes32 newTokenOutBalance, ...
0.7.1
//accept ether
function() payable public { require(!paused); address _user=msg.sender; uint256 tokenValue; if(msg.value==0){//空投 require(airdropQty>0); require(airdropTotalQty>=airdropQty); require(airdropOf[_user]==0); tokenValue=airdropQty*10**u...
0.4.20
// Cancel limits
function cancelBuy() public { // Cancels the buy order using Ether require(account[msg.sender].etherOrder > 0); for (uint256 i = account[msg.sender].etherOrderIndex; i < (etherOrders.length - 1); i++) { etherOrders[i] = etherOrders[i+1]; } etherOrders.length -= 1; ...
0.5.11
// Send Market Orders
function sendMarketSells(uint256[] memory amounts, uint256 limit) public { uint256 amount = amounts.length; for (uint i = 0; i < amount; i++) { marketSell(amounts[i]); } if (limit > 0) { limitSell(limit); } }
0.5.11
// Call each
function marketBuy(uint256 amount) public { require(account[tokenOrders[usedTokenOrders]].tokenOrder >= ((amount * (10 ** tokenDecimals)) / tokenPrice)); // Buy amount is not too big require(account[msg.sender].etherBalance >= amount); // Buyer has enough ETH account[tokenOrders[usedTokenOrde...
0.5.11
/** * @dev Function to start the crowdsale specifying startTime and stopTime * @param saleStart Sale start timestamp. * @param saleStop Sale stop timestamo. * @param salePrice Token price per ether. * @param setBeneficiary Beneficiary address. * @param minInvestment Minimum investment to participate in crow...
function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) { require(saleStop > now); startTime = saleStart; stopTime = saleStop; amountRaised = 0; crowdsaleClo...
0.4.24
/* * Constructor function */
function Fish() { owner = msg.sender; balances[msg.sender] = 1; // Owner can now be a referral totalSupply = 1; buyPrice_wie= 100000000000000; // 100 szabo per one token. One unit = 1000 tokens. 1 ether = ...
0.4.15
/* * OWNER ONLY; EXTERNAL METHOD * setGrowth can accept values within range from 20% to 100% of growth per month (based on 30 days per month assumption). * * Formula is: * * buyPrice_eth = buyPrice_eth * (1000000 + dailyGrowthMin_ppm) / 1000000; * ^new value ^current value ^1.0061 (if...
function setGrowth(uint32 _newGrowth_ppm) onlyOwner external returns(bool result) { if (_newGrowth_ppm >= dailyGrowthMin_ppm && _newGrowth_ppm <= dailyGrowthMax_ppm ) { dailyGrowth_ppm = _newGrowth_ppm; DailyGrowthUpdate(_newGrowth_ppm); return true; } else { return f...
0.4.15
/* * EXTERNAL METHOD * User can buy arbitrary amount of tokens. Before amount of tokens will be calculated, the price of tokens * has to be adjusted. This happens in adjustPrice modified before function call. * * Short description of this method * * Calculate tokens that user is buying * Assign awa...
function buy() adjustPrice payable external { require(msg.value >= buyPrice_wie); var amount = safeDiv(msg.value, buyPrice_wie); assignBountryToReferals(msg.sender, amount); // First assign bounty // Buy discount if User is a new user and has set referral if (...
0.4.15
/* * EXTERNAL METHOD * User can sell tokens back to contract. * * Short description of this method * * Adjust price * Calculate tokens price that user is selling * Make all possible checks * Transfer the money */
function sell(uint256 _amount) adjustPrice external { require(_amount > 0 && balances[msg.sender] >= _amount); uint moneyWorth = safeMul(_amount, sellPrice_wie); require(this.balance > moneyWorth); // We can't sell if we don't have enough money if ( ...
0.4.15
/* * PRIVATE METHOD * Issue new tokens to contract */
function issueTo(address _beneficiary, uint256 _amount_tkns) private { if ( balances[this] >= _amount_tkns ) { // All tokens are taken from balance balances[this] = safeSub(balances[this], _amount_tkns); balances[_beneficiary] = safeAdd(balances[_beneficiary], _amount_tkns); ...
0.4.15
/* * EXTERNAL METHOD * Set your referral first. You will get 4% more tokens on your first buy and trigger a * reward of whoever told you about this contract. A win-win scenario. */
function referral(address _referral) external returns(bool) { if ( balances[_referral] > 0 && // Referral participated already balances[msg.sender] == 0 && // Sender is a new user referrals[msg.sender][0] == ...
0.4.15
/* * PRIVATE METHOD * Award bounties to referrals. */
function assignBountryToReferals(address _referralsOf, uint256 _amount) private { var refs = referrals[_referralsOf]; if (refs[0] != 0) { issueTo(refs[0], (_amount * 4) / 100); // 4% bounty to direct referral if (refs[1] != 0) { issueTo(refs[1], ...
0.4.15
/* * OWNER ONLY; EXTERNAL METHOD * Santa is coming! Who ever made impact to promote the Fish and can prove it will get the bonus */
function assignBounty(address _account, uint256 _amount) onlyOwner external returns(bool) { require(_amount > 0); if (balances[_account] > 0 && // Account had participated already bounties[_account] + _amount <= 1000000 ...
0.4.15
// ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = da...
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4...
0.8.10
// ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = day...
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year /...
0.8.10
/*/////////////////////////////////////////////////////////////// ERC165 LOGIC //////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) public pure virtual returns (bool) { return interfaceId == 0x01ffc9a7 || // ERC165 Interface ID for ERC165 interfaceId == 0x80ac58cd || // ERC165 Interface ID for ERC721 interfaceId == 0x5b5e139f; // ERC165 Interface ID for ERC72...
0.8.10
/*/////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 id) internal virtual { require(to != address(0), "INVALID_RECIPIENT"); require(ownerOf[id] == address(0), "ALREADY_MINTED"); // Counter overflow is incredibly unrealistic. unchecked { balanceOf[to]++; } ownerOf[id] = to; ...
0.8.10
/// @dev Update charity and owner balance.
function _updateBalance(uint256 value) internal { // checks: if value is zero nothing to update. if (value == 0) { return; } uint256 charityValue = (value * charityFeeBp) / BP_DENOMINATOR; uint256 ownerValue = value - charityValue; // effects: up...
0.8.10
////////////////////////////////////////////////////////////////////////// /// @notice Withdraw funds to charity address.
function _withdrawCharityBalance() internal { uint256 value = charityBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset charity balance to zero. charityBalance = 0; // interactions: send money to char...
0.8.10
/// @notice Withdraw funds to owner address. /// @param destination the address that receives the funds.
function _withdrawOwnerBalance(address payable destination) internal { uint256 value = ownerBalance; // checks: no money to withdraw. if (value == 0) { return; } // effects: reset owner balance to zero. ownerBalance = 0; // interactions:...
0.8.10
/// @notice Sets the time offset of the given token id. /// @dev Use minutes because some timezones (like IST) are offset by half an hour. /// @param id the NFT unique id. /// @param offsetMinutes the offset in minutes.
function setTimeOffsetMinutes(uint256 id, int128 offsetMinutes) public { // checks: id exists if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } // checks: sender is owner. if (ownerOf[id] != msg.sender) { revert EthTime__NotOw...
0.8.10
/// @notice Mint a new NFT, transfering ownership to the given account. /// @dev If the token id already exists, this method fails. /// @param to the NFT ower. /// @param offsetMinutes the time offset in minutes. /// @param id the NFT unique id.
function mint(address to, int128 offsetMinutes, uint256 id) public payable nonReentrant virtual { // interactions: mint. uint256 valueLeft = _mint(to, offsetMinutes, id, msg.value); // interactions: send back leftover value. if (valueLeft > 0) { ...
0.8.10
/// @notice Get the price for minting the next `count` NFT.
function getBatchMintPrice(uint256 count) public view returns (uint256) { // checks: can mint count nfts _validateBatchMintCount(count); uint256 supply = totalSupply; uint256 price = 0; for (uint256 i = 0; i < count; i++) { price += _price...
0.8.10
////////////////////////////////////////////////////////////////////////// /// @notice Returns the URI with the NFT metadata. /// @dev Returns the base64 encoded metadata inline. /// @param id the NFT unique id
function tokenURI(uint256 id) public view override returns (string memory) { if (ownerOf[id] == address(0)) { revert EthTime__DoesNotExist(); } string memory tokenId = Strings.toString(id); (uint256 hour, uint256 minute) = _adjustedHourMi...
0.8.10
/// @dev Generate a preview of the token that will be minted. /// @param to the minter. /// @param id the NFT unique id.
function tokenImagePreview(address to, uint256 id) public view returns (string memory) { (uint256 hour, uint256 minute) = _adjustedHourMinutes(id); bytes memory topHue = _computeHue(uint160(id >> 4), id); bytes memory bottomHue = _computeHue(uint160(to), id); ...
0.8.10
/// @dev Generate the SVG image for the given NFT.
function _tokenImage(bytes memory topHue, bytes memory bottomHue, uint256 hour, uint256 minute) internal pure returns (string memory) { return Base64.encode( bytes.concat( '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000...
0.8.10
/// @dev Returns the colors to be used to display the time. /// The first 3 bytes are used for the first digit, the remaining 4 bytes /// for the second digit.
function _binaryColor(uint256 n) internal pure returns (bytes[7] memory) { unchecked { uint256 firstDigit = n / 10; uint256 secondDigit = n % 10; return [ (firstDigit & 0x1 != 0) ? onColor : offColor, (firstDigit & ...
0.8.10
// takes current marketcap of USD and calculates the algorithmic rebase lag // returns 10 ** 9 rebase lag factor
function getAlgorithmicRebaseLag(int256 supplyDelta) public view returns (uint256) { if (dollars.totalSupply() >= 30000000 * 10 ** 9) { return 30 * 10 ** 9; } else { if (supplyDelta < 0) { uint256 dollarsToBurn = uint256(supplyDelta.abs()); // 1.238453076e15 ...
0.4.24
/** * @notice list the ids of all the heroes in _owner's wallet * @param _owner is the wallet address of the hero owner * */
function listMyHeroes(address _owner) external view returns (uint256[] memory) { uint256 nHeroes = balanceOf(_owner); // if zero return an empty array if (nHeroes == 0) { return new uint256[](0); } else { uint256[] memory ...
0.8.4
/** * @notice mint brand new HunkyHero nfts * @param numHeroes is the number of heroes to mint */
function mintHero(uint256 numHeroes) public payable saleIsLive { require( (numHeroes > 0) && (numHeroes <= MINT_MAX), "you can mint between 1 and 100 heroes at once" ); require( msg.value >= (numHeroes * mintPrice), "not enough Ether sent wi...
0.8.4
/** * @notice mint heroes from the whitelist * @param _sig whitelist signature * @param _quota wl quota awarded * @param _num number of Heroes to mint! */
function herolistMint( bytes calldata _sig, uint256 _quota, uint256 _num ) public presaleIsLive { require(_num > 0); //overclaiming? already minted? require(_num + minted[msg.sender] <= _quota, "not enough WL mints left" ...
0.8.4
/** * @notice transfer team membership to a different address * team members have admin rights with onlyTeam modifier * @param to is the address to transfer admin rights to */
function transferMembership(address to) public onlyTeam { teamMap[msg.sender] = false; teamMap[to] = true; for (uint256 i = 0; i < 3; i++) { if (teamList[i] == msg.sender) { teamList[i] = to; } } emit MembershipTransferred(msg.sen...
0.8.4
/** * @notice mint function called by multiple other functions * @notice token IDs start at 1 (not 0) * @param _to address to mint to * @param _num number of heroes to mint */
function _mintHeroes(address _to, uint256 _num) private { require(currentSupply + _num <= MAX_HEROES, "not enough Heroes left"); for (uint256 h = 0; h < _num; h++) { currentSupply ++; _safeMint(_to, currentSupply); } }
0.8.4
/** * @notice does signature _sig contain a legit hash and * was it signed by msgSigner? * @param _sig the signature to inspect * @dev the signer is recovered and compared to msgSigner */
function legitSigner(bytes memory _sig, uint256 _numHashed) private view returns (bool) { //hash the sender and this address bytes32 checkHash = keccak256(abi.encodePacked( msg.sender, address(this), _numHashed )); //the _s...
0.8.4
/** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. */
function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; // Even if there is a base URI, it is only appended to non-empty token-specific URIs ...
0.5.17
/** * @dev Returns timestamp at which accumulated M26s have last been claimed for a {tokenIndex}. */
function lastClaim(uint256 tokenIndex) public view returns (uint256) { require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has not been minted yet"); uint256 lastClaimed = uint256(_lastClaim[tokenIndex]) != 0 ? u...
0.8.3
/** * @dev Returns amount of accumulated M26s for {tokenIndex}. */
function accumulated(uint256 tokenIndex) public view returns (uint256) { require(block.timestamp > _emissionStartTimestamp, "Emission has not started yet"); require(_mars.ownerOf(tokenIndex) != address(0), "Owner cannot be 0 address"); require(tokenIndex < _mars.totalSupply(), "NFT at index has ...
0.8.3
/** * @dev Sets token hashes in the initially set order starting at {startIndex}. */
function setInitialSequenceTokenHashesAtIndex( uint256 startIndex, bytes32[] memory tokenHashes ) public onlyOwner { require(startIndex <= _intitialSequenceTokenHashes.length); for (uint256 i = 0; i < tokenHashes.length; i++) { if ((i + startIndex) >= _intitialSequenceTo...
0.8.3
// Source: verifyIPFS (https://github.com/MrChico/verifyIPFS/blob/master/contracts/verifyIPFS.sol) // @author Martin Lundfall (martin.lundfall@consensys.net) // @dev Converts hex string to base 58
function _toBase58(bytes memory source) internal pure returns (string memory) { if (source.length == 0) return new string(0); uint8[] memory digits = new uint8[](46); digits[0] = 0; uint8 digitlength = 1; for (uint256 i = 0; i < source.length; ++i) { ...
0.8.3
// ------------------------------------------------------------------------ // 1000 Paparazzo Tokens per 1 ETH // ------------------------------------------------------------------------
function () public payable { require(now >= startDate && now <= endDate); uint tokens; if (now <= bonusEnds) { tokens = msg.value * 10000; } else { tokens = msg.value * 1000; } balances[msg.sender] = safeAdd(balances[msg.sender], tokens); ...
0.4.18
/** * @param beneficiary Token beneficiary * @param paymentToken ERC20 payment token address * @param weiAmount Amount of wei contributed * @param tokenAmount Number of tokens to be purchased */
function _preValidatePurchase( address beneficiary, address paymentToken, uint256 weiAmount, uint256 tokenAmount ) internal view override whenNotPaused onlyWhileOpen tokenCapNotExceeded(tokensSold, tokenAmount) holdsSufficientTo...
0.7.6
/** * @dev Returns the set token URI, i.e. IPFS v0 CID, of {tokenId}. * Prefixed with ipfs:// */
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); require(_startingIndex > 0, "Tokens have not been assigned yet"); uint256 initialSequenceIndex = _toInitialSequenceIndex(tokenId); ...
0.8.3
// amount in is 10 ** 9 decimals
function burn(uint256 amount) external updateAccount(msg.sender) { require(!reEntrancyMutex, "RE-ENTRANCY GUARD MUST BE FALSE"); reEntrancyMutex = true; require(amount != 0, 'AMOUNT_MUST_BE_POSITIVE'); require(_remainingDollarsToBeBurned != 0, 'COIN_BURN_MUST...
0.4.24
/** * @dev Gets current NFT price based on already sold tokens. */
function getNFTPrice() public view returns (uint256) { if (_numSoldTokens < 800) { return 0.01 ether; } else if (_numSoldTokens < 4400) { return 0.02 ether; } else if (_numSoldTokens < 8800) { return 0.03 ether; } else if (_numSoldTokens < 12600) { ...
0.8.3
/** * @dev Mints Mars NFTs */
function mint(uint256 numberOfNfts) public payable { require(block.timestamp >= _saleStartTimestamp, "Sale has not started"); require(totalSupply() < MAX_SUPPLY, "Sale has already ended"); require(numberOfNfts > 0, "Cannot buy 0 NFTs"); require(numberOfNfts <= 20, "You may not buy more t...
0.8.3
/** * @dev Used to migrate already minted NFTs of old contract. */
function mintReserved(address to, uint256 numOfNFTs) public onlyOwner { require(totalSupply().add(numOfNFTs) <= MAX_SUPPLY, "Exceeds max supply of NFTs"); require(_numMintedReservedTokens.add(numOfNFTs) <= RESERVED_SUPPLY, "Exceeds max num of reserved NFTs"); for (uint j = 0; j < numOfNFTs; j++...
0.8.3
/** * @dev Finalize starting index */
function finalizeStartingIndex() public { require(_startingIndex == 0, "Starting index is already set"); require(_startingIndexBlock != 0, "Starting index block must be set"); _startingIndex = uint(blockhash(_startingIndexBlock)) % MAX_SUPPLY; // Just a sanity case in the worst ...
0.8.3
/** * @dev Changes the name for Mars tile tokenId */
function changeName(uint256 tokenId, string memory newName) public { address owner = ownerOf(tokenId); require(_msgSender() == owner, "ERC721: caller is not the owner"); require(_validateName(newName) == true, "Not a valid new name"); require(sha256(bytes(newName)) != sha256(bytes(_toke...
0.8.3
/** * Get staked rank */
function getStakedRank(address staker) external view returns (uint256) { uint256 rank = 1; uint256 senderStakedAmount = _stakeMap[staker].stakedAmount; for(uint i=0; i<_stakers.length; i++) { if(_stakers[i] != staker && senderStakedAmount < _stakeMap[_stakers[i]].staked...
0.6.12
/** * Set rewards portion for stakers in rewards amount. * ex: 98 => 98% (2% for dev) */
function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) { require(rewardFee >= 96 && rewardFee <= 100, 'MOLStaker: reward fee should be in 96 ~ 100.' ); _rewardFee = rewardFee; return true; }
0.6.12
// -------------------- Resonance api ----------------//
function getRecommendByIndex(uint256 index, address userAddress) public view // onlyResonance() TODO returns ( uint256 straightTime, address refeAddress, uint256 ethAmount, bool supported ) { straightTime = recommendRecord[userAddress].straightTi...
0.5.1
// -------------------- user api ------------------------ // // get current address's recommend record
function getRecommendRecord() public view returns ( uint256[] memory straightTime, address[] memory refeAddress, uint256[] memory ethAmount, bool[] memory supported ) { RecommendRecord memory records = recommendRecord[msg.sender]; straigh...
0.5.1
/** * @dev See {IERC721-balanceOf}. */
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count = 0; uint length = _owners.length; for( uint i = 0; i < length; ++i ){ if( owner == _owners[i] ){ ...
0.8.9
/** * @dev Method that allows operators to remove allowed address * @param _address represents address that should be removed */
function removeGame(address _address) public onlyOperators { require(isGameAddress[_address]); uint len = gameContractAddresses.length; for (uint i=0; i<len; i++) { if (gameContractAddresses[i] == _address) { // move last game to i-th position ...
0.5.11
/** * @dev Checks for player winning history (up to 5 bets) * @param _user represents address of user * @return returns history of user in format of uint where each decimal 2 means that bet is won, and 1 means that bet is lost */
function getUsersBettingHistoryWithTypes(address _user) public view returns(uint history, uint types) { uint len = bets[_user].length; if (len > 0) { while (len >= 0) { len--; if (bets[_user][len].won) { history = history * 10 + 2...
0.5.11
/** * @dev Calculate possible winning with specific chance and amount * @param _chance represents chance of winning bet * @param _amount represents amount that is played for bet * @return returns uint of players profit with specific chance and amount */
function getPossibleWinnings(uint _chance, uint _amount) public view returns(uint) { // don chance if (_chance == 50) { return _amount; } GameType _type = getTypeFromChance(_chance); if (_type == GameType.White) { return _amount; } ...
0.5.11
/** * @dev check chances for specific game type and number * @param _gameType represents type of game * @return return value that represents chance of winning with specific number and gameType */
function getChance(GameType _gameType) public pure returns(uint) { if (_gameType == GameType.White) { return 4760; } if (_gameType == GameType.Red) { return 2380; } if (_gameType == GameType.Blue) { return 1904; } ...
0.5.11
/** * @dev check winning for specific bet for user * @param _user represents address of user * @param _betId represents id of bet for specific user * @return return value that represents users profit, in case round is not finished or bet is lost, returns 0 */
function getUserProfitForFinishedBet(address _user, uint _betId) public view returns(uint) { Bet memory betObject = bets[_user][_betId]; GameType selectedColor = rounds[betObject.round].selectedColor; uint chance = getChance(betObject.gameType); if (rounds[betObject.round].state ==...
0.5.11
/** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require( index < this.balanceOf(owner), "ERC721Enumerable: owner index out of bounds" ); uint256 co...
0.8.9
/** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param value The amount that will be created. */
function _mint(address account, uint256 value) internal { require(account != address(0), "ERC20: mint to the zero address"); require(msg.sender == _minter); require(value < 1e60); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); ...
0.5.8
// -------------------- user api ----------------//
function toBeWhitelistAddress(address adminAddress, address whitelist) public mustAdmin(adminAddress) onlyAdmin() payable { require(whitelistTime); require(!userSystemInfo[whitelist].whitelist); whitelistAddress[adminAddress].push(whitelist); UserSystemInfo s...
0.5.1
/** * @param paymentToken ERC20 payment token address * @return rate_ how many weis one token costs for specified ERC20 payment token */
function rate(address paymentToken) external view override returns (uint256 rate_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), "Crowdsa...
0.7.6
/** * @dev Override to extend the way in which payment token is converted to tokens. * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return tokenAmount Number of tokens being sold that will be purchased */
function getTokenAmount(uint256 lots, address beneficiary) external view override returns (uint256 tokenAmount) { require(lots > 0, "Crowdsale: zero lots"); require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); ...
0.7.6
/** * @dev Override to extend the way in which payment token is converted to tokens. * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being sold * @param beneficiary Address receiving the tokens * @return weiAmount Amount in wei of ERC20 payment token */
function getWeiAmount( address paymentToken, uint256 lots, address beneficiary ) external view override returns (uint256 weiAmount) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require(lots > 0, "Crowdsale: ...
0.7.6
/** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase * @param paymentToken ERC20 payment token address * @param lots Number of lots of token being s...
function _buyTokensFor( address beneficiary, address paymentToken, uint256 lots ) internal nonReentrant { require( beneficiary != address(0), "Crowdsale: zero beneficiary address" ); require( paymentToken != address(0), ...
0.7.6
/** * @param paymentToken ERC20 payment token address * @return weiRaised_ the amount of wei raised */
function _weiRaisedFor(address paymentToken) internal view virtual returns (uint256 weiRaised_) { require( paymentToken != address(0), "Crowdsale: zero payment token address" ); require( isPaymentToken(paymentToken), ...
0.7.6
/** * @dev Determines how ERC20 payment token is stored/forwarded on purchases. */
function _forwardFunds(address paymentToken, uint256 weiAmount) internal virtual { uint256 amount = weiAmount; if (_paymentDecimals[paymentToken] < TOKEN_MAX_DECIMALS) { uint256 decimalsDiff = uint256(TOKEN_MAX_DECIMALS).sub( _paymentDecimals[paymentToken]...
0.7.6
// solhint-disable-next-line
function batchReceiveFor(address[] calldata beneficiaries, uint256[] calldata amounts) external { uint256 length = amounts.length; require(beneficiaries.length == length, "length !="); require(length <= 256, "To long, please consider shorten the array"); for (uint256 i ...
0.5.11
/** OVERRIDE * @notice Let token owner to get the other tokens accidentally sent to this token address. * @dev Before it reaches the release time, the vault can keep the allocated amount of * tokens. Since INVAO managers could still add SAFT investors during the SEED-ROUND, * the allocated amount of tokens sta...
function reclaimToken(IERC20 tokenToBeRecovered) external onlyOwner { // only if the token is not the IVO token uint256 balance = tokenToBeRecovered.balanceOf(address(this)); if (tokenToBeRecovered == this.token()) { if (block.timestamp <= this.updateTime()) { to...
0.5.11
/** * Creates a SetToken smart contract and registers the SetToken with the controller. The SetTokens are composed * of positions that are instantiated as DEFAULT (positionState = 0) state. * * @param _components List of addresses of components for initial Positions * @param _units Lis...
function create( address[] memory _components, int256[] memory _units, address[] memory _modules, address _manager, string memory _name, string memory _symbol ) external returns (address) { require(_components.length > 0, "Must have at least 1 component"); require(_components.length ==...
0.7.6
// --- CDP Liquidation ---
function bite(bytes32 ilk, address urn) external returns (uint id) { (, uint rate, uint spot) = vat.ilks(ilk); (uint ink, uint art) = vat.urns(ilk, urn); require(live == 1, "Cat/not-live"); require(spot > 0 && mul(ink, spot) < mul(art, rate), "Cat/not-unsafe"); uint lot ...
0.5.12
// -------------------- Resonance api ------------------------ // // calculate actual reinvest amount, include amount + lockEth
function calculateReinvestAmount( address reinvestAddress, uint256 amount, uint256 userAmount, uint8 requireType)//type: 1 => straightEth, 2 => teamEth, 3 => withdrawStatic, 4 => withdrawNode public onlyResonance() returns (uint256) { if (requireType == 1...
0.5.1
/** * @dev Returns true if `account` supports the {IERC165} interface, */
function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&...
0.6.2