comment
stringlengths
11
2.99k
function_code
stringlengths
165
3.15k
version
stringclasses
80 values
/** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; }
0.6.2
/** * @dev Internal function to invoke `onApprovalReceived` on a target address * The call is not executed if the target address is not a contract * @param spender address The address which will spend the funds * @param value uint256 The amount of tokens to be spent * @param data bytes Optional data to send along with the call * @return whether the call correctly returned the expected magic value */
function _checkAndCallApprove(address spender, uint256 value, bytes memory data) internal returns (bool) { if (!spender.isContract()) { return false; } bytes4 retval = IERC1363Spender(spender).onApprovalReceived( _msgSender(), value, data ); return (retval == _ERC1363_APPROVED); }
0.6.2
/** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } }
0.8.9
/** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */
function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); }
0.8.9
/** * @dev Gets the value of the bits between left and right, both inclusive, in the given integer. * 31 is the leftmost bit, 0 is the rightmost bit. * * For example: bitsFrom(10, 3, 1) == 7 (101 in binary), because 10 is *101*0 in binary * bitsFrom(10, 2, 0) == 2 (010 in binary), because 10 is 1*010* in binary */
function bitsFrom(uint integer, uint left, uint right) external pure returns (uint) { require(left >= right, "left > right"); require(left <= 31, "left > 31"); uint delta = left - right + 1; return (integer & (((1 << delta) - 1) << right)) >> right; }
0.8.7
/** * @dev Copies a string into `dst` starting at `dstIndex` with a maximum length of `dstLen`. * This function will not write beyond `dstLen`. However, if `dstLen` is not reached, it may write zeros beyond the length of the string. */
function copyString(string memory src, bytes memory dst, uint dstIndex, uint dstLen) internal pure returns (uint) { uint srcIndex; uint srcLen = bytes(src).length; for (; srcLen > 31 && srcIndex < srcLen && srcIndex < dstLen - 31; srcIndex += 32) { memcpy32(src, srcIndex, dst, dstIndex + srcIndex); } for (; srcIndex < srcLen && srcIndex < dstLen; ++srcIndex) { memcpy1(src, srcIndex, dst, dstIndex + srcIndex); } return dstIndex + srcLen; }
0.8.7
/** * @dev Adds `str` to the end of the internal buffer. */
function pushToStringBuffer(StringBuffer memory self, string memory str) internal pure returns (StringBuffer memory) { if (self.buffer.length == self.numberOfStrings) { string[] memory newBuffer = new string[](self.buffer.length * 2); for (uint i = 0; i < self.buffer.length; ++i) { newBuffer[i] = self.buffer[i]; } self.buffer = newBuffer; } self.buffer[self.numberOfStrings] = str; self.numberOfStrings++; self.totalStringLength += bytes(str).length; return self; }
0.8.7
/** * @dev Concatenates `str` to the end of the last string in the internal buffer. */
function concatToLastString(StringBuffer memory self, string memory str) internal pure { if (self.numberOfStrings == 0) { self.numberOfStrings++; } uint idx = self.numberOfStrings - 1; self.buffer[idx] = string(abi.encodePacked(self.buffer[idx], str)); self.totalStringLength += bytes(str).length; }
0.8.7
/** * @notice Converts the contents of the StringBuffer into a string. * @dev This runs in O(n) time. */
function get(StringBuffer memory self) internal pure returns (string memory) { bytes memory output = new bytes(self.totalStringLength); uint ptr = 0; for (uint i = 0; i < self.numberOfStrings; ++i) { ptr = copyString(self.buffer[i], output, ptr, self.totalStringLength); } return string(output); }
0.8.7
/** * @notice Appends a string to the end of the StringBuffer * @dev Internally the StringBuffer keeps a `string[]` that doubles in size when extra capacity is needed. */
function append(StringBuffer memory self, string memory str) internal pure { uint idx = self.numberOfStrings == 0 ? 0 : self.numberOfStrings - 1; if (bytes(self.buffer[idx]).length + bytes(str).length <= 1024) { concatToLastString(self, str); } else { pushToStringBuffer(self, str); } }
0.8.7
/** * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership */
function initialize(ENSSubdomainRegistrar _registrar) public onlyInit { initialized(); registrar = _registrar; ens = registrar.ens(); registrar.pointRootNode(this); // Check APM has all permissions it needss ACL acl = ACL(kernel().acl()); require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS); require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS); }
0.4.24
/** * Claims all Brainz from all staked Bit Monsters the caller owns. */
function claimBrainz() external { uint count = bitMonsters.balanceOf(msg.sender); uint total = 0; for (uint i = 0; i < count; ++i) { uint tokenId = bitMonsters.tokenOfOwnerByIndex(msg.sender, i); uint rewards = calculateRewards(tokenId); if (rewards > 0) { tokenIdToTimestamp[tokenId] = block.timestamp - ((block.timestamp - tokenIdToTimestamp[tokenId]) % 86400); } total += rewards; } _mint(msg.sender, total); }
0.8.7
/** * Stake your Brainz a-la OSRS Duel Arena. * * 50% chance of multiplying your Brainz by 1.9x rounded up. * 50% chance of losing everything you stake. */
function stake(uint count) external returns (bool won) { require(count > 0, "Must stake at least one BRAINZ"); require(balanceOf(msg.sender) >= count, "You don't have that many tokens"); Rng memory rn = rng; if (rn.generate(0, 1) == 0) { _mint(msg.sender, (count - count / 10) * 1 ether); won = true; } else { _burn(msg.sender, count * 1 ether); won = false; } rng = rn; }
0.8.7
// n: node id d: direction r: return node id // Return existential state of a node. n == HEAD returns list existence.
function exists(CLL storage self, uint n) internal constant returns (bool) { if (self.cll[n][PREV] != HEAD || self.cll[n][NEXT] != HEAD) return true; if (n == HEAD) return false; if (self.cll[HEAD][NEXT] == n) return true; return false; }
0.4.20
// Can be used before `insert` to build an ordered list // `a` an existing node to search from, e.g. HEAD. // `b` value to seek // `r` first node beyond `b` in direction `d`
function seek(CLL storage self, uint a, uint b, bool d) internal constant returns (uint r) { r = step(self, a, d); while ((b!=r) && ((b < r) != d)) r = self.cll[r][d]; return; }
0.4.20
/** * @notice Create new repo in registry with `_name` and first repo version * @param _name Repo name * @param _dev Address that will be given permission to create versions * @param _initialSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */
function newRepoWithVersion( string _name, address _dev, uint16[3] _initialSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_REPO_ROLE) returns (Repo) { Repo repo = _newRepo(_name, this); // need to have permissions to create version repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI); // Give permissions to _dev ACL acl = ACL(kernel().acl()); acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE()); acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE()); acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE()); return repo; }
0.4.24
/** * @notice Create new version for repo * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */
function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); }
0.4.24
// https://ipfs.tokemaklabs.xyz/ipfs/Qmf5Vuy7x5t3rMCa6u57hF8AE89KLNkjdxSKjL8USALwYo/0x4eff3562075c5d2d9cb608139ec2fe86907005fa.json
function claimRewards( uint256 cycle, uint256 amount, uint8 v, bytes32 r, bytes32 s // bytes calldata signature ) external whenNotPaused { ITokemakRewards.Recipient memory recipient = ITokemakRewards.Recipient( 1, // chainId cycle, address(this), // wallet amount ); ITokemakRewards(rewards).claim(recipient, v, r, s); emit ClaimRewards( msg.sender, address(TOKE_TOKEN_ADDRESS), address(this), amount ); }
0.8.4
/// Constructor initializes the contract ///@param initialSupply Initial supply of tokens ///@param tokenName Display name if the token ///@param tokenSymbol Token symbol ///@param decimalUnits Number of decimal points for token holding display ///@param _redemptionPercentageOfDistribution The whole percentage number (0-100) of the total distributable profit amount available for token redemption in each profit distribution round
function AquaToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits, uint8 _redemptionPercentageOfDistribution, address _priceOracle ) public { totalSupplyOfTokens = initialSupply; holdings.add(msg.sender, LibHoldings.Holding({ totalTokens : initialSupply, lockedTokens : 0, lastRewardNumber : 0, weiBalance : 0 })); name = tokenName; // Set the name for display purposes symbol = tokenSymbol; // Set the symbol for display purposes decimals = decimalUnits; // Amount of decimals for display purposes redemptionPercentageOfDistribution = _redemptionPercentageOfDistribution; priceOracle = AquaPriceOracle(_priceOracle); owner = msg.sender; tokenStatus = TokenStatus.OnSale; rewards.push(0); }
0.4.20
///Token holders can call this function to request to redeem (sell back to ///the company) part or all of their tokens ///@param _numberOfTokens Number of tokens to redeem ///@return Redemption request ID (required in order to cancel this redemption request)
function requestRedemption(uint256 _numberOfTokens) public returns (uint) { require(tokenStatus == TokenStatus.Trading && _numberOfTokens > 0); LibHoldings.Holding storage h = holdings.get(msg.sender); require(h.totalTokens.sub( h.lockedTokens) >= _numberOfTokens); // Check if the sender has enough uint redemptionId = redemptionsQueue.add(msg.sender, _numberOfTokens); h.lockedTokens = h.lockedTokens.add(_numberOfTokens); RequestRedemption(msg.sender, _numberOfTokens, redemptionId); return redemptionId; }
0.4.20
///Token holders can call this function to cancel a redemption request they ///previously submitted using requestRedemption function ///@param _requestId Redemption request ID
function cancelRedemptionRequest(uint256 _requestId) public { require(tokenStatus == TokenStatus.Trading && redemptionsQueue.exists(_requestId)); LibRedemptions.Redemption storage r = redemptionsQueue.get(_requestId); require(r.holderAddress == msg.sender); LibHoldings.Holding storage h = holdings.get(msg.sender); h.lockedTokens = h.lockedTokens.sub(r.numberOfTokens); uint numberOfTokens = r.numberOfTokens; redemptionsQueue.remove(_requestId); CancelRedemptionRequest(msg.sender, numberOfTokens, _requestId); }
0.4.20
///The function returns token holder details given token holder account address ///@param _holder Account address of a token holder ///@return totalTokens Total tokens held by this token holder ///@return lockedTokens The number of tokens (out of the total held but this token holder) that are locked and await redemption to be processed ///@return weiBalance Wei balance of the token holder available for withdrawal.
function getHolding(address _holder) public constant returns (uint totalTokens, uint lockedTokens, uint weiBalance) { if (!holdings.exists(_holder)) { totalTokens = 0; lockedTokens = 0; weiBalance = 0; return; } LibHoldings.Holding storage h = holdings.get(_holder); totalTokens = h.totalTokens; lockedTokens = h.lockedTokens; uint stepsMade; (weiBalance, stepsMade) = calcFullWeiBalance(h, 0); return; }
0.4.20
///Token owner calls this function to progress profit distribution round ///@param maxNumbeOfSteps Maximum number of steps in this progression ///@return False in case profit distribution round has completed
function continueDistribution(uint maxNumbeOfSteps) public returns (bool) { require(tokenStatus == TokenStatus.Distributing); if (continueRedeeming(maxNumbeOfSteps)) { ContinueDistribution(true); return true; } uint tokenReward = distCtx.totalRewardAmount.div( totalSupplyOfTokens ); rewards.push(tokenReward); uint paidReward = tokenReward.mul(totalSupplyOfTokens); uint unusedDistributionAmount = distCtx.totalRewardAmount.sub(paidReward); if (unusedDistributionAmount > 0) { if (!holdings.exists(owner)) { holdings.add(owner, LibHoldings.Holding({ totalTokens : 0, lockedTokens : 0, lastRewardNumber : rewards.length.sub(1), weiBalance : unusedDistributionAmount })); } else { LibHoldings.Holding storage ownerHolding = holdings.get(owner); ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedDistributionAmount); } } tokenStatus = TokenStatus.Trading; DistributionCompleted(distCtx.receivedRedemptionAmount.sub(distCtx.redemptionAmount), paidReward, unusedDistributionAmount); ContinueDistribution(false); return false; }
0.4.20
///Token holder can call this function to withdraw their balance (dividend ///and redemption payments) while limiting the number of operations (in the ///extremely unlikely case when withdrawBalance function exceeds gas limit) ///@param maxSteps Maximum number of steps to take while withdrawing holder balance
function withdrawBalanceMaxSteps(uint maxSteps) public { require(holdings.exists(msg.sender)); LibHoldings.Holding storage h = holdings.get(msg.sender); uint updatedBalance; uint stepsMade; (updatedBalance, stepsMade) = calcFullWeiBalance(h, maxSteps); h.weiBalance = 0; h.lastRewardNumber = h.lastRewardNumber.add(stepsMade); bool balanceRemainig = h.lastRewardNumber < rewards.length.sub(1); if (h.totalTokens == 0 && h.weiBalance == 0) holdings.remove(msg.sender); msg.sender.transfer(updatedBalance); WithdrawBalance(msg.sender, updatedBalance, balanceRemainig); }
0.4.20
///Token holders can call this method to permanently destroy their tokens. ///WARNING: Burned tokens cannot be recovered! ///@param numberOfTokens Number of tokens to burn (permanently destroy) ///@return True if operation succeeds
function burn(uint256 numberOfTokens) external returns (bool success) { require(holdings.exists(msg.sender)); if (numberOfTokens == 0) { Burn(msg.sender, numberOfTokens); return true; } LibHoldings.Holding storage fromHolding = holdings.get(msg.sender); require(fromHolding.totalTokens.sub(fromHolding.lockedTokens) >= numberOfTokens); // Check if the sender has enough updateWeiBalance(fromHolding, 0); fromHolding.totalTokens = fromHolding.totalTokens.sub(numberOfTokens); // Subtract from the sender if (fromHolding.totalTokens == 0 && fromHolding.weiBalance == 0) holdings.remove(msg.sender); totalSupplyOfTokens = totalSupplyOfTokens.sub(numberOfTokens); Burn(msg.sender, numberOfTokens); return true; }
0.4.20
///Token owner to call this to initiate final distribution in case of project wind-up
function windUp() onlyOwner public payable { require(tokenStatus == TokenStatus.Trading); tokenStatus = TokenStatus.WindingUp; uint totalWindUpAmount = msg.value; uint tokenReward = msg.value.div(totalSupplyOfTokens); rewards.push(tokenReward); uint paidReward = tokenReward.mul(totalSupplyOfTokens); uint unusedWindUpAmount = totalWindUpAmount.sub(paidReward); if (unusedWindUpAmount > 0) { if (!holdings.exists(owner)) { holdings.add(owner, LibHoldings.Holding({ totalTokens : 0, lockedTokens : 0, lastRewardNumber : rewards.length.sub(1), weiBalance : unusedWindUpAmount })); } else { LibHoldings.Holding storage ownerHolding = holdings.get(owner); ownerHolding.weiBalance = ownerHolding.weiBalance.add(unusedWindUpAmount); } } WindingUpStarted(msg.value); }
0.4.20
/** * Generates a random Bit Monster. * * 9/6666 bit monsters will be special, which means they're prebuilt images instead of assembled from the 6 attributes a normal Bit Monster has. * All 9 specials are guaranteed to be minted by the time all 6666 Bit Monsters are minted. * The chance of a special at each roll is roughly even, although there's a slight dip in chance in the mid-range. */
function generateBitMonster(Rng memory rn, bool[9] memory ms) internal returns (BitMonster memory) { uint count = bitMonsters.totalSupply(); int ub = 6666 - int(count) - 1 - (90 - int(mintedSpecialsCount) * 10); if (ub < 0) { ub = 0; } BitMonster memory m; if (rn.generate(0, uint(ub)) <= (6666 - count) / 666) { m = BitMonsterGen.generateSpecialBitMonster(rn, ms); } else { m = BitMonsterGen.generateUnspecialBitMonster(rn); } if (m.special != Special.NONE) { mintedSpecialsCount++; } rng = rn; return m; }
0.8.7
/** * Mints some Bit Monsters. * * @param count The number of Bit Monsters to mint. Must be >= 1 and <= 10. * You must send 0.06 ETH for each Bit Monster you want to mint. */
function mint(uint count) external payable { require(count >= 1 && count <= 10, "Count must be >=1 and <=10"); require(!Address.isContract(msg.sender), "Contracts cannot mint"); require(mintingState != MintingState.NotAllowed, "Minting is not allowed atm"); if (mintingState == MintingState.WhitelistOnly) { require(whitelist[msg.sender] >= 1000 + count, "Not enough whitelisted mints"); whitelist[msg.sender] -= count; } require(msg.value == count * 0.06 ether, "Send exactly 0.06 ETH for each mint"); Rng memory rn = rng; bool[9] memory ms = mintedSpecials; for (uint i = 0; i < count; ++i) { bitMonsters.createBitMonster(generateBitMonster(rn, ms), msg.sender); } rng = rn; mintedSpecials = ms; Address.sendValue(payHere, msg.value); }
0.8.7
/// @notice Extracts the r, s, and v components from the `sigData` field starting from the `offset` /// @dev Note: does not do any bounds checking on the arguments! /// @param sigData the signature data; could be 1 or more packed signatures. /// @param offset the offset in sigData from which to start unpacking the signature components.
function extractSignature(bytes memory sigData, uint256 offset) internal pure returns (bytes32 r, bytes32 s, uint8 v) { // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { let dataPointer := add(sigData, offset) r := mload(add(dataPointer, 0x20)) s := mload(add(dataPointer, 0x40)) v := byte(0, mload(add(dataPointer, 0x60))) } return (r, s, v); }
0.5.10
/** * @dev claimTokens() provides airdrop winners the function of collecting their tokens */
function claimTokens() ifNotPaused public { Contribution storage contrib = contributions[msg.sender]; require(contrib.isValid, "Address not found in airdrop list"); require(contrib.tokenAmount > 0, "There are currently no tokens to claim."); uint256 tempPendingTokens = contrib.tokenAmount; contrib.tokenAmount = 0; totalTokensClaimed = totalTokensClaimed.add(tempPendingTokens); contrib.wasClaimed = true; ERC20(tokenAddress).transfer(msg.sender, tempPendingTokens); }
0.4.25
/** * Returns the metadata of the Bit Monster corresponding to the given tokenId as a base64-encoded JSON object. Meant for use with OpenSea. * * @dev This function can take a painful amount of time to run, sometimes exceeding 9 minutes in length. Use getBitMonster() instead for frontends. */
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "the token doesn't exist"); string memory metadataRaw = metadata.getMetadataJson(tokenId); string memory metadataB64 = Base64.encode(bytes(metadataRaw)); return string(abi.encodePacked( "data:application/json;base64,", metadataB64 )); }
0.8.7
/// @dev Called when the receiver of transfer is contract /// @param _sender address the address of tokens sender /// @param _value uint256 the amount of tokens to be transferred. /// @param _data bytes data that can be attached to the token transation
function tokenFallback(address _sender, uint _value, bytes _data) external returns (bool ok) { if (!supportsToken(msg.sender)) { return false; } // Problem: This will do a sstore which is expensive gas wise. Find a way to keep it in memory. // Solution: Remove the the data tkn = Tkn(msg.sender, _sender, _value); __isTokenFallback = true; if (!address(this).delegatecall(_data)) { __isTokenFallback = false; return false; } // avoid doing an overwrite to .token, which would be more expensive // makes accessing .tkn values outside tokenPayable functions unsafe __isTokenFallback = false; return true; }
0.4.18
/// @dev initialize the contract.
function initialize() private returns (bool success) { R1 = token1.balanceOf(this); R2 = token2.balanceOf(this); // one reserve should be full and the second should be empty success = ((R1 == 0 && R2 == S2) || (R2 == 0 && R1 == S1)); if (success) { operational = true; } }
0.4.18
/// @dev the price of token1 in terms of token2, represented in 18 decimals. /// price = (S1 - R1) / (S2 - R2) * (S2 / S1)^2 /// @param _R1 uint256 reserve of the first token /// @param _R2 uint256 reserve of the second token /// @param _S1 uint256 total supply of the first token /// @param _S2 uint256 total supply of the second token
function getPrice(uint256 _R1, uint256 _R2, uint256 _S1, uint256 _S2) public constant returns (uint256 price) { price = PRECISION; price = price.mul(_S1.sub(_R1)); price = price.div(_S2.sub(_R2)); price = price.mul(_S2); price = price.div(_S1); price = price.mul(_S2); price = price.div(_S1); }
0.4.18
/// @dev get a quote for exchanging and update temporary reserves. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @return the return amount of the buying token
function quoteAndReserves(address _fromToken, uint256 _inAmount, address _toToken) private isOperational returns (uint256 returnAmount) { // if buying token2 from token1 if (token1 == _fromToken && token2 == _toToken) { // add buying amount to the temp reserve l_R1 = R1.add(_inAmount); // calculate the other reserve l_R2 = calcReserve(l_R1, S1, S2); if (l_R2 > R2) { return 0; } // the returnAmount is the other reserve difference returnAmount = R2.sub(l_R2); } // if buying token1 from token2 else if (token2 == _fromToken && token1 == _toToken) { // add buying amount to the temp reserve l_R2 = R2.add(_inAmount); // calculate the other reserve l_R1 = calcReserve(l_R2, S2, S1); if (l_R1 > R1) { return 0; } // the returnAmount is the other reserve difference returnAmount = R1.sub(l_R1); } else { return 0; } }
0.4.18
/// @dev get a quote for exchanging. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @return the return amount of the buying token
function quote(address _fromToken, uint256 _inAmount, address _toToken) public constant isOperational returns (uint256 returnAmount) { uint256 _R1; uint256 _R2; // if buying token2 from token1 if (token1 == _fromToken && token2 == _toToken) { // add buying amount to the temp reserve _R1 = R1.add(_inAmount); // calculate the other reserve _R2 = calcReserve(_R1, S1, S2); if (_R2 > R2) { return 0; } // the returnAmount is the other reserve difference returnAmount = R2.sub(_R2); } // if buying token1 from token2 else if (token2 == _fromToken && token1 == _toToken) { // add buying amount to the temp reserve _R2 = R2.add(_inAmount); // calculate the other reserve _R1 = calcReserve(_R2, S2, S1); if (_R1 > R1) { return 0; } // the returnAmount is the other reserve difference returnAmount = R1.sub(_R1); } else { return 0; } }
0.4.18
/// @dev calculate second reserve from the first reserve and the supllies. /// @dev formula: R2 = S2 * (S1 - sqrt(R1 * S1 * 2 - R1 ^ 2)) / S1 /// @dev the equation is simetric, so by replacing _S1 and _S2 and _R1 with _R2 we can calculate the first reserve from the second reserve /// @param _R1 the first reserve /// @param _S1 the first total supply /// @param _S2 the second total supply /// @return _R2 the second reserve
function calcReserve(uint256 _R1, uint256 _S1, uint256 _S2) public pure returns (uint256 _R2) { _R2 = _S2 .mul( _S1 .sub( _R1 .mul(_S1) .mul(2) .sub( _R1 .toPower2() ) .sqrt() ) ) .div(_S1); }
0.4.18
/// @dev change tokens. /// @param _fromToken the token to sell from /// @param _inAmount the amount to sell /// @param _toToken the token to buy /// @param _minReturn the munimum token to buy /// @return the return amount of the buying token
function change(address _fromToken, uint256 _inAmount, address _toToken, uint256 _minReturn) public canTrade returns (uint256 returnAmount) { // pull transfer the selling token require(ERC20(_fromToken).transferFrom(msg.sender, this, _inAmount)); // exchange the token returnAmount = exchange(_fromToken, _inAmount, _toToken, _minReturn); if (returnAmount == 0) { // if no return value revert revert(); } // transfer the buying token ERC20(_toToken).transfer(msg.sender, returnAmount); // validate the reserves require(validateReserves()); Change(_fromToken, _inAmount, _toToken, returnAmount, msg.sender); }
0.4.18
/// @dev allow admin to withraw excess tokens accumulated due to precision
function withdrawExcessReserves() public onlyOwner returns (uint256 returnAmount) { // if there is excess of token 1, transfer it to the owner if (token1.balanceOf(this) > R1) { returnAmount = returnAmount.add(token1.balanceOf(this).sub(R1)); token1.transfer(msg.sender, token1.balanceOf(this).sub(R1)); } // if there is excess of token 2, transfer it to the owner if (token2.balanceOf(this) > R2) { returnAmount = returnAmount.add(token2.balanceOf(this).sub(R2)); token2.transfer(msg.sender, token2.balanceOf(this).sub(R2)); } }
0.4.18
/// @dev Should be called by external mechanism when reward funds are sent to this contract
function notifyRewardAmount(uint256 reward) external override nonReentrant onlyRewardDistributor updateReward(address(0)) { // overflow fix according to https://sips.synthetix.io/sips/sip-77 require(reward < uint(-1) / 1e18, "the notified reward cannot invoke multiplication overflow"); if (block.timestamp >= periodFinish) { rewardRate = reward.div(duration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(duration); } lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(duration); emit RewardAdded(reward); }
0.6.12
////////////////////////////////////////////////// ////////////////////////////////////////////////// ////////////////////////////////////////////////// /// @notice Withdraw portion of allocation unlocked
function withdraw() public onlyOwner { uint256 timestamp = block.timestamp; if (timestamp == lastWithdrawalTimestamp) return; uint256 _lastWithdrawalTimestamp = lastWithdrawalTimestamp; lastWithdrawalTimestamp = timestamp; uint256 balance = premia.balanceOf(address(this)); if (timestamp >= endTimestamp) { premia.safeTransfer(msg.sender, balance); } else { uint256 elapsedSinceLastWithdrawal = timestamp.sub(_lastWithdrawalTimestamp); uint256 timeLeft = endTimestamp.sub(_lastWithdrawalTimestamp); premia.safeTransfer(msg.sender, balance.mul(elapsedSinceLastWithdrawal).div(timeLeft)); } }
0.7.6
/* * @param characterType * @param adversaryType * @return whether adversaryType is a valid type of adversary for a given character */
function isValidAdversary(uint8 characterType, uint8 adversaryType) pure returns (bool) { if (characterType >= KNIGHT_MIN_TYPE && characterType <= KNIGHT_MAX_TYPE) { // knight return (adversaryType <= DRAGON_MAX_TYPE); } else if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { // wizard return (adversaryType < BALLOON_MIN_TYPE || adversaryType > BALLOON_MAX_TYPE); } else if (characterType >= DRAGON_MIN_TYPE && characterType <= DRAGON_MAX_TYPE) { // dragon return (adversaryType >= WIZARD_MIN_TYPE); } else if (characterType >= ARCHER_MIN_TYPE && characterType <= ARCHER_MAX_TYPE) { // archer return ((adversaryType >= BALLOON_MIN_TYPE && adversaryType <= BALLOON_MAX_TYPE) || (adversaryType >= KNIGHT_MIN_TYPE && adversaryType <= KNIGHT_MAX_TYPE)); } return false; }
0.4.24
/** * pick a random adversary. * @param nonce a nonce to make sure there's not always the same adversary chosen in a single block. * @return the index of a random adversary character * */
function getRandomAdversary(uint256 nonce, uint8 characterType) internal view returns(uint16) { uint16 randomIndex = uint16(generateRandomNumber(nonce) % numCharacters); // use 7, 11 or 13 as step size. scales for up to 1000 characters uint16 stepSize = numCharacters % 7 == 0 ? (numCharacters % 11 == 0 ? 13 : 11) : 7; uint16 i = randomIndex; //if the picked character is a knight or belongs to the sender, look at the character + stepSizes ahead in the array (modulo the total number) //will at some point return to the startingPoint if no character is suited do { if (isValidAdversary(characterType, characters[ids[i]].characterType) && characters[ids[i]].owner != msg.sender) { return i; } i = (i + stepSize) % numCharacters; } while (i != randomIndex); return INVALID_CHARACTER_INDEX; }
0.4.24
/** * Hits the character of the given type at the given index. * Wizards can knock off two protections. Other characters can do only one. * @param index the index of the character * @param nchars the number of characters * @return the value gained from hitting the characters (zero is the character was protected) * */
function hitCharacter(uint16 index, uint16 nchars, uint8 characterType) internal returns(uint128 characterValue) { uint32 id = ids[index]; uint8 knockOffProtections = 1; if (characterType >= WIZARD_MIN_TYPE && characterType <= WIZARD_MAX_TYPE) { knockOffProtections = 2; } if (protection[id] >= knockOffProtections) { protection[id] = protection[id] - knockOffProtections; return 0; } characterValue = characters[ids[index]].value; nchars--; replaceCharacter(index, nchars); }
0.4.24
/** * finds the oldest character * */
function findOldest() public { uint32 newOldest = noKing; for (uint16 i = 0; i < numCharacters; i++) { if (ids[i] < newOldest && characters[ids[i]].characterType <= DRAGON_MAX_TYPE) newOldest = ids[i]; } oldest = newOldest; }
0.4.24
/* @dev distributes castle loot among archers */
function distributeCastleLoot(uint32 characterId) public onlyUser { require(castleTreasury > 0, "empty treasury"); Character archer = characters[characterId]; require(archer.characterType >= ARCHER_MIN_TYPE && archer.characterType <= ARCHER_MAX_TYPE, "only archers can access the castle treasury"); if(lastCastleLootDistributionTimestamp[characterId] == 0) require(now - archer.purchaseTimestamp >= config.castleLootDistributionThreshold(), "not enough time has passed since the purchase"); else require(now >= lastCastleLootDistributionTimestamp[characterId] + config.castleLootDistributionThreshold(), "not enough time passed since the last castle loot distribution"); require(archer.fightCount >= 3, "need to fight 3 times"); lastCastleLootDistributionTimestamp[characterId] = now; archer.fightCount = 0; uint128 luckFactor = generateLuckFactor(uint128(generateRandomNumber(characterId) % 1000)); if (luckFactor < 3) { luckFactor = 3; } assert(luckFactor <= 50); uint128 amount = castleTreasury * luckFactor / 100; archer.value += amount; castleTreasury -= amount; emit NewDistributionCastleLoot(amount, characterId, luckFactor); }
0.4.24
/** * sell the character of the given id * throws an exception in case of a knight not yet teleported to the game * @param characterId the id of the character * */
function sellCharacter(uint32 characterId, uint16 characterIndex) public onlyUser { if (characterIndex >= numCharacters || characterId != ids[characterIndex]) characterIndex = getCharacterIndex(characterId); Character storage char = characters[characterId]; require(msg.sender == char.owner, "only owners can sell their characters"); require(char.characterType < BALLOON_MIN_TYPE || char.characterType > BALLOON_MAX_TYPE, "balloons are not sellable"); require(char.purchaseTimestamp + 1 days < now, "character can be sold only 1 day after the purchase"); uint128 val = char.value; numCharacters--; replaceCharacter(characterIndex, numCharacters); msg.sender.transfer(val); if (oldest == 0) findOldest(); emit NewSell(characterId, msg.sender, val); }
0.4.24
/** * Knights, balloons, wizards, and archers are only entering the game completely, when they are teleported to the scene * @param id the character id * */
function teleportCharacter(uint32 id) internal { // ensure we do not teleport twice require(teleported[id] == false, "already teleported"); teleported[id] = true; Character storage character = characters[id]; require(character.characterType > DRAGON_MAX_TYPE, "dragons do not need to be teleported"); //this also makes calls with non-existent ids fail addCharacter(id, numCharacters); numCharacters++; numCharactersXType[character.characterType]++; emit NewTeleport(id); }
0.4.24
/** * returns 10 characters starting from a certain indey * @param startIndex the index to start from * @return 4 arrays containing the ids, types, values and owners of the characters * */
function get10Characters(uint16 startIndex) constant public returns(uint32[10] characterIds, uint8[10] types, uint128[10] values, address[10] owners) { uint32 endIndex = startIndex + 10 > numCharacters ? numCharacters : startIndex + 10; uint8 j = 0; uint32 id; for (uint16 i = startIndex; i < endIndex; i++) { id = ids[i]; characterIds[j] = id; types[j] = characters[id].characterType; values[j] = characters[id].value; owners[j] = characters[id].owner; j++; } }
0.4.24
/** @notice This function adds liquidity to Mushroom vaults with ETH or ERC20 tokens @param fromToken The token used for entry (address(0) if ether) @param amountIn The amount of fromToken to invest @param toVault Harvest vault address @param minMVTokens The minimum acceptable quantity vault tokens to receive. Reverts otherwise @param intermediateToken Token to swap fromToken to before entering vault @param swapTarget Excecution target for the swap or zap @param swapData DEX or Zap data @param affiliate Affiliate address @param shouldSellEntireBalance True if amountIn is determined at execution time (i.e. contract is caller) @return tokensReceived- Quantity of Vault tokens received */
function ZapIn( address fromToken, uint256 amountIn, address toVault, uint256 minMVTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, bool shouldSellEntireBalance ) external payable stopInEmergency returns (uint256 tokensReceived) { require( approvedTargets[swapTarget] || swapTarget == address(0), "Target not Authorized" ); // get incoming tokens uint256 toInvest = _pullTokens( fromToken, amountIn, affiliate, true, shouldSellEntireBalance ); // get intermediate token uint256 intermediateAmt = _fillQuote( fromToken, intermediateToken, toInvest, swapTarget, swapData ); // Deposit to Vault tokensReceived = _vaultDeposit(intermediateAmt, toVault, minMVTokens); }
0.5.17
/** * @dev Mints a new token up to the current supply, stopping at the max supply. */
function mintNFTeacher(uint256 _quantity) public payable override { require(mintStart <= block.timestamp, 'Minting not started.'); require(MAX_PER_TX >= _quantity, 'Too many mints.'); require(currentMaxSupply >= tokenIds.current() + _quantity, 'No more tokens, currently.'); require(MAX_SUPPLY >= tokenIds.current() + _quantity, 'No more tokens, ever.'); require(MINT_PRICE * _quantity == msg.value, 'Wrong value sent.'); for (uint8 i = 0; i < _quantity; i++) { tokenIds.increment(); _safeMint(msg.sender, tokenIds.current()); } }
0.8.9
/// @dev The receive function is triggered when FTM is received
receive() external payable virtual { // check ERC20 token balances while we have the chance, if we send FTM it will forward them for (uint256 i = 0; i < royaltyERC20Tokens.length; i++) { // send the tokens to the recipients IERC20 _token = IERC20(royaltyERC20Tokens[i]); if (_token.balanceOf(address(this)) > 0) { this.withdrawTokens(royaltyERC20Tokens[i]); } } // withdraw the splits this.withdraw(); }
0.8.9
// import balance for a group of user with a specific contract terms
function importBalance(address[] memory buyers, uint256[] memory tokens, string memory contractName) public onlyOwner whenNotPaused returns (bool) { require(buyers.length == tokens.length, "buyers and balances mismatch"); VestingContract storage vestingContract = _vestingContracts[contractName]; require(vestingContract.basisPoints.length > 0, "contract does not exist"); for(uint256 i = 0; i < buyers.length; i++) { require(tokens[i] > 0, "cannot import zero balance"); BuyerInfo storage buyerInfo = _buyerInfos[buyers[i]]; require(buyerInfo.total == 0, "have already imported balance for this buyer"); buyerInfo.total = tokens[i]; buyerInfo.contractName = contractName; } emit ImportBalance(buyers, tokens, contractName); return true; }
0.5.9
// the number of token can be claimed by the msg.sender at the moment
function claimableToken() public view returns (uint256) { BuyerInfo storage buyerInfo = _buyerInfos[msg.sender]; if(buyerInfo.claimed < buyerInfo.total) { VestingContract storage vestingContract = _vestingContracts[buyerInfo.contractName]; uint256 currentMonth = block.timestamp.sub(_deployTime).div(_month); if(currentMonth < vestingContract.startMonth) { return uint256(0); } if(currentMonth >= vestingContract.endMonth) { // vest the unclaimed token all at once so there's no remainder return buyerInfo.total.sub(buyerInfo.claimed); } else { uint256 claimableIndex = currentMonth.sub(vestingContract.startMonth); uint256 canClaim = 0; for(uint256 i = 0; i <= claimableIndex; ++i) { canClaim = canClaim.add(vestingContract.basisPoints[i]); } return canClaim.mul(buyerInfo.total).div(10000).sub(buyerInfo.claimed); } } return uint256(0); }
0.5.9
/** * @dev Checks if amount is within allowed burn bounds and * destroys `amount` tokens from `account`, reducing the * total supply. * @param account account to burn tokens for * @param amount amount of tokens to burn * * Emits a {Burn} event */
function _burn(address account, uint256 amount) internal virtual override { require(amount >= burnMin, "BurnableTokenWithBounds: below min burn bound"); require(amount <= burnMax, "BurnableTokenWithBounds: exceeds max burn bound"); super._burn(account, amount); emit Burn(account, amount); }
0.8.0
/* * @dev Verifies if message was signed by owner to give access to _add for this contract. * Assumes Geth signature prefix. * @param _add Address of agent with access * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. * @return Validity of access message for a given address. */
function isInvalidAccessMessage( uint8 _v, bytes32 _r, bytes32 _s) view public returns (bool) { bytes32 hash = keccak256(abi.encodePacked(this)); address signAddress = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), _v, _r, _s ); if (ownerAddy == signAddress){ return true; } else{ return false; } }
0.8.7
/* * @dev Public Sale Mint * @param quantity Number of NFT's to be minted at 0.06 with a max of 10 per transaction. This is a gas efficient function. */
function mint(uint256 quantity) external payable { require(quantity <= 10, "Cant mint more than 10"); require(totalSupply() + quantity <= 3183, "Sold out"); require(msg.value >= pricePerPublic * quantity, "Not enough Eth"); require(publicLive, "sale not live"); _safeMint(msg.sender, quantity); }
0.8.7
/* * @dev Verifies if message was signed by owner to give access to this contract. * Assumes Geth signature prefix. * @param quantity Number of NFT's to be minted at 0.04 with a max of 3. This is a gas efficient function. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameters r. * @param _s ECDSA signature parameters s. */
function mintWL(uint256 quantity, uint8 _v, bytes32 _r, bytes32 _s) external payable noInvalidAccess(_v, _r, _s){ require(quantity <= 3, "Cant mint more than 3"); require(totalSupply() + quantity <= 3183, "Sold out"); require(msg.value >= pricePerWL * quantity, "Not enough Eth"); require(presaleLive, "sale not live"); require(WLminted[msg.sender] + quantity <= 3, "Cant mint more than 3"); WLminted[msg.sender] += quantity; _safeMint(msg.sender, quantity); }
0.8.7
/** * @dev Stake `_value` ions on behalf of `_from` * @param _from The address of the target * @param _value The amount to stake * @return true on success */
function stakeFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance stakedBalance[_from] = stakedBalance[_from].add(_value); // Add to the targeted staked balance emit Stake(_from, _value); return true; }
0.5.4
/** * @dev See {IMerkleDrop-isClaimed}. */
function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; }
0.7.5
/** * @dev See {IMerkleDrop-claim}. */
function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), "MerkleDrop: drop already claimed"); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), "MerkleDrop: invalid proof"); // Mark it claimed and send the token. _setClaimed(index); token.safeTransfer(account, amount); emit Claimed(index, account, amount); }
0.7.5
/** * @dev See {IMerkleDrop-stop}. */
function stop(address beneficiary) external override onlyOwner { require(beneficiary != address(0), "MerkleDrop: beneficiary is the zero address"); // solhint-disable-next-line not-rely-on-time require(block.timestamp >= expireTimestamp, "MerkleDrop: not expired"); uint256 amount = token.balanceOf(address(this)); token.safeTransfer(beneficiary, amount); emit Stopped(beneficiary, amount); }
0.7.5
/** * @dev Store `_value` from `_from` to `_to` in escrow * @param _from The address of the sender * @param _to The address of the recipient * @param _value The amount of network ions to put in escrow * @return true on success */
function escrowFrom(address _from, address _to, uint256 _value) public inWhitelist returns (bool) { require (balanceOf[_from] >= _value); // Check if the targeted balance is enough balanceOf[_from] = balanceOf[_from].sub(_value); // Subtract from the targeted balance escrowedBalance[_to] = escrowedBalance[_to].add(_value); // Add to the targeted escrowed balance emit Escrow(_from, _to, _value); return true; }
0.5.4
/** * @dev Release escrowed `_value` from `_from` * @param _from The address of the sender * @param _value The amount of escrowed network ions to be released * @return true on success */
function unescrowFrom(address _from, uint256 _value) public inWhitelist returns (bool) { require (escrowedBalance[_from] >= _value); // Check if the targeted escrowed balance is enough escrowedBalance[_from] = escrowedBalance[_from].sub(_value); // Subtract from the targeted escrowed balance balanceOf[_from] = balanceOf[_from].add(_value); // Add to the targeted balance emit Unescrow(_from, _value); return true; }
0.5.4
/** * Transfer ions between public key addresses in a Name * @param _nameId The ID of the Name * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */
function transferBetweenPublicKeys(address _nameId, address _from, address _to, uint256 _value) public returns (bool success) { require (AOLibrary.isName(_nameId)); require (_nameTAOPosition.senderIsAdvocate(msg.sender, _nameId)); require (!_nameAccountRecovery.isCompromised(_nameId)); // Make sure _from exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _from)); // Make sure _to exist in the Name's Public Keys require (_namePublicKey.isKeyExist(_nameId, _to)); _transfer(_from, _to, _value); return true; }
0.5.4
/** * @dev Check if neither account is blacklisted before performing transfer * If transfer recipient is a redemption address, burns tokens * @notice Transfer to redemption address will burn tokens with a 1 cent precision * @param sender address of sender * @param recipient address of recipient * @param amount amount of tokens to transfer */
function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require(!isBlacklisted[sender], "FavorCurrency: sender is blacklisted"); require(!isBlacklisted[recipient], "FavorCurrency: recipient is blacklisted"); if (isRedemptionAddress(recipient)) { super._transfer(sender, recipient, amount.sub(amount.mod(CENT))); _burn(recipient, amount.sub(amount.mod(CENT))); } else { super._transfer(sender, recipient, amount); } }
0.8.0
/** * @dev Requere neither accounts to be blacklisted before approval * @param owner address of owner giving approval * @param spender address of spender to approve for * @param amount amount of tokens to approve */
function _approve( address owner, address spender, uint256 amount ) internal override { require(!isBlacklisted[owner], "FavorCurrency: tokens owner is blacklisted"); require(!isBlacklisted[spender] || amount == 0, "FavorCurrency: tokens spender is blacklisted"); super._approve(owner, spender, amount); }
0.8.0
/// @dev withdraw native tokens divided by splits
function withdraw(Payout storage _payout) external onlyWhenInitialized(_payout.initialized) { uint256 _amount = address(this).balance; if (_amount > 0) { for (uint256 i = 0; i < _payout.recipients.length; i++) { // we don't want to fail here or it can lock the contract withdrawals uint256 _share = (_amount * _payout.splits[i]) / _payout.BASE; (bool _success, ) = payable(_payout.recipients[i]).call{value: _share}(''); if (_success) { emit SplitWithdrawal(address(0), _payout.recipients[i], _share); } } } }
0.8.9
/// @dev withdraw ERC20 tokens divided by splits
function withdrawTokens(Payout storage _payout, address _tokenContract) external onlyWhenInitialized(_payout.initialized) { IERC20 tokenContract = IERC20(_tokenContract); // transfer the token from address of this contract uint256 _amount = tokenContract.balanceOf(address(this)); /* istanbul ignore else */ if (_amount > 0) { for (uint256 i = 0; i < _payout.recipients.length; i++) { uint256 _share = i != _payout.recipients.length - 1 ? (_amount * _payout.splits[i]) / _payout.BASE : tokenContract.balanceOf(address(this)); tokenContract.transfer(_payout.recipients[i], _share); emit SplitWithdrawal(_tokenContract, _payout.recipients[i], _share); } } }
0.8.9
/// @dev withdraw ERC721 tokens to the first recipient
function withdrawNFT( Payout storage _payout, address _tokenContract, uint256[] memory _id ) external onlyWhenInitialized(_payout.initialized) { IERC721 tokenContract = IERC721(_tokenContract); for (uint256 i = 0; i < _id.length; i++) { address _recipient = getNftRecipient(_payout); tokenContract.safeTransferFrom(address(this), _recipient, _id[i]); } }
0.8.9
/// @dev Allow a recipient to update to a new address
function updateRecipient(Payout storage _payout, address _recipient) external onlyWhenInitialized(_payout.initialized) { require(_recipient != address(0), 'Cannot use the zero address.'); require(_recipient != address(this), 'Cannot use the address of this contract.'); // loop over all the recipients and update the address bool _found = false; for (uint256 i = 0; i < _payout.recipients.length; i++) { // if the sender matches one of the recipients, update the address if (_payout.recipients[i] == msg.sender) { _payout.recipients[i] = _recipient; _found = true; break; } } require(_found, 'The sender is not a recipient.'); }
0.8.9
// Transfer token with data and signature
function transferAndData(address _to, uint _value, string _data) returns (bool) { //Default assumes totalSupply can't be over max (2^256 - 1). if (balances[msg.sender] >= _value && balances[_to] + _value >= balances[_to]) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } }
0.4.13
/** @dev updates one of the token reserves can only be called by the owner @param _reserveToken address of the reserve token @param _ratio constant reserve ratio, represented in ppm, 1-1000000 @param _enableVirtualBalance true to enable virtual balance for the reserve, false to disable it @param _virtualBalance new reserve's virtual balance */
function updateReserve(IERC20Token _reserveToken, uint32 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validReserve(_reserveToken) validReserveRatio(_ratio) { Reserve storage reserve = reserves[_reserveToken]; require(totalReserveRatio - reserve.ratio + _ratio <= MAX_CRR); // validate input totalReserveRatio = totalReserveRatio - reserve.ratio + _ratio; reserve.ratio = _ratio; reserve.isVirtualBalanceEnabled = _enableVirtualBalance; reserve.virtualBalance = _virtualBalance; }
0.4.16
// ------------------------------------------------------------------------ // Withdraw accumulated rewards // ------------------------------------------------------------------------
function ClaimReward() external { require(PendingReward(msg.sender) > 0, "No pending rewards"); uint256 _pendingReward = PendingReward(msg.sender); // Global stats update totalRewards = totalRewards.add(_pendingReward); // update the record users[msg.sender].totalGained = users[msg.sender].totalGained.add(_pendingReward); users[msg.sender].lastClaimedDate = now; users[msg.sender].pendingGains = 0; // mint more tokens inside token contract equivalent to _pendingReward require(IERC20(OXS).transfer(msg.sender, _pendingReward)); emit RewardsCollected(_pendingReward); }
0.6.0
// ------------------------------------------------------------------------ // This will stop the existing staking // ------------------------------------------------------------------------
function StopStaking() external { require(users[msg.sender].activeDeposit >= 0, "No active stake"); uint256 _activeDeposit = users[msg.sender].activeDeposit; // update staking stats // check if we have any pending rewards, add it to previousGains var users[msg.sender].pendingGains = PendingReward(msg.sender); // update amount users[msg.sender].activeDeposit = 0; // reset last claimed figure as well users[msg.sender].lastClaimedDate = now; // withdraw the tokens and move from contract to the caller require(IERC20(OXS).transfer(msg.sender, _activeDeposit)); emit StakingStopped(_activeDeposit); }
0.6.0
//#########################################################################################################################################################// //##########################################################FARMING QUERIES################################################################################// //#########################################################################################################################################################// // ------------------------------------------------------------------------ // Query to get the pending reward // @param _caller address of the staker // ------------------------------------------------------------------------
function PendingReward(address _caller) public view returns(uint256 _pendingRewardWeis){ uint256 _totalStakingTime = now.sub(users[_caller].lastClaimedDate); uint256 _reward_token_second = ((stakingRate).mul(10 ** 21)).div(365 days); // added extra 10^21 uint256 reward = ((users[_caller].activeDeposit).mul(_totalStakingTime.mul(_reward_token_second))).div(10 ** 23); // remove extra 10^21 // 10^2 are for 100 (%) return reward.add(users[_caller].pendingGains); }
0.6.0
//#########################################################################################################################################################// //################################################################COMMON UTILITIES#########################################################################// //#########################################################################################################################################################// // ------------------------------------------------------------------------ // Internal function to add new deposit // ------------------------------------------------------------------------
function _newDeposit(uint256 _amount) internal{ require(users[msg.sender].activeDeposit == 0, "Already running, use funtion add to stake"); // add that token into the contract balance // check if we have any pending reward, add it to pendingGains variable users[msg.sender].pendingGains = PendingReward(msg.sender); users[msg.sender].activeDeposit = _amount; users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount); users[msg.sender].startTime = now; users[msg.sender].lastClaimedDate = now; // update global stats totalStakes = totalStakes.add(_amount); }
0.6.0
// ------------------------------------------------------------------------ // Internal function to add to existing deposit // ------------------------------------------------------------------------
function _addToExisting(uint256 _amount) internal{ require(users[msg.sender].activeDeposit > 0, "no running farming/stake"); // update staking stats // check if we have any pending reward, add it to pendingGains variable users[msg.sender].pendingGains = PendingReward(msg.sender); // update current deposited amount users[msg.sender].activeDeposit = users[msg.sender].activeDeposit.add(_amount); // update total deposits till today users[msg.sender].totalDeposits = users[msg.sender].totalDeposits.add(_amount); // update new deposit start time -- new stake will begin from this time onwards users[msg.sender].startTime = now; // reset last claimed figure as well -- new stake will begin from this time onwards users[msg.sender].lastClaimedDate = now; // update global stats totalStakes = totalStakes.add(_amount); }
0.6.0
/** @dev returns the expected return for buying the token for a reserve token @param _reserveToken reserve token contract address @param _depositAmount amount to deposit (in the reserve token) @return expected purchase return amount */
function getPurchaseReturn(IERC20Token _reserveToken, uint256 _depositAmount) public constant active validReserve(_reserveToken) returns (uint256) { Reserve storage reserve = reserves[_reserveToken]; require(reserve.isPurchaseEnabled); // validate input uint256 tokenSupply = token.totalSupply(); uint256 reserveBalance = getReserveBalance(_reserveToken); uint256 amount = extensions.formula().calculatePurchaseReturn(tokenSupply, reserveBalance, reserve.ratio, _depositAmount); // deduct the fee from the return amount uint256 feeAmount = getConversionFeeAmount(amount); return safeSub(amount, feeAmount); }
0.4.16
/** @dev converts a specific amount of _fromToken to _toToken @param _fromToken ERC20 token to convert from @param _toToken ERC20 token to convert to @param _amount amount to convert, in fromToken @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero @return conversion return amount */
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) { require(_fromToken != _toToken); // validate input // conversion between the token and one of its reserves if (_toToken == token) return buy(_fromToken, _amount, _minReturn); else if (_fromToken == token) return sell(_toToken, _amount, _minReturn); // conversion between 2 reserves uint256 purchaseAmount = buy(_fromToken, _amount, 1); return sell(_toToken, purchaseAmount, _minReturn); }
0.4.16
/** @dev utility, returns the expected return for selling the token for one of its reserve tokens, given a total supply override @param _reserveToken reserve token contract address @param _sellAmount amount to sell (in the standard token) @param _totalSupply total token supply, overrides the actual token total supply when calculating the return @return sale return amount */
function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _totalSupply) private constant active validReserve(_reserveToken) greaterThanZero(_totalSupply) returns (uint256) { Reserve storage reserve = reserves[_reserveToken]; uint256 reserveBalance = getReserveBalance(_reserveToken); uint256 amount = extensions.formula().calculateSaleReturn(_totalSupply, reserveBalance, reserve.ratio, _sellAmount); // deduct the fee from the return amount uint256 feeAmount = getConversionFeeAmount(amount); return safeSub(amount, feeAmount); }
0.4.16
// get normal cardlist;
function getNormalCardList(address _owner) external view returns(uint256[],uint256[]){ uint256 len = getNormalCard(_owner); uint256[] memory itemId = new uint256[](len); uint256[] memory itemNumber = new uint256[](len); uint256 startId; uint256 endId; (startId,endId) = schema.productionCardIdRange(); uint256 i; while (startId <= endId) { if (cards.getOwnedCount(_owner,startId)>=1) { itemId[i] = startId; itemNumber[i] = cards.getOwnedCount(_owner,startId); i++; } startId++; } return (itemId, itemNumber); }
0.4.21
/** * Mint Doges by owner */
function reserveDoges(address _to, uint256 _numberOfTokens) external onlyOwner { require(_to != address(0), "Invalid address to reserve."); uint256 supply = totalSupply(); uint256 i; for (i = 0; i < _numberOfTokens; i++) { _safeMint(_to, supply + i); } }
0.7.6
/** * Mints tokens */
function mintDoges(uint256 numberOfTokens) external payable { require(saleIsActive, "Sale must be active to mint"); require(numberOfTokens <= maxToMint, "Invalid amount to mint per once"); require(totalSupply().add(numberOfTokens) <= MAX_DOGE_SUPPLY, "Purchase would exceed max supply"); require(mintPrice.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct"); for(uint256 i = 0; i < numberOfTokens; i++) { uint256 mintIndex = totalSupply(); _safeMint(msg.sender, mintIndex); } // If we haven't set the starting index and this is either // 1) the last saleable token or 2) the first token to be sold after // the reveal time, set the starting index block if (startingIndexBlock == 0 && (totalSupply() == MAX_DOGE_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) { startingIndexBlock = block.number; } }
0.7.6
//withdraw an amount including any want balance
function _withdraw(uint256 amount) internal returns (uint256) { uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this)); uint256 looseBalance = want.balanceOf(address(this)); uint256 total = balanceUnderlying.add(looseBalance); if (amount.add(dustThreshold) >= total) { //cant withdraw more than we own. so withdraw all we can if(balanceUnderlying > dustThreshold){ require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "ctoken: redeemAll fail"); } looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } if (looseBalance >= amount) { want.safeTransfer(address(strategy), amount); return amount; } //not state changing but OK because of previous call uint256 liquidity = want.balanceOf(address(cToken)); if (liquidity > 1) { uint256 toWithdraw = amount.sub(looseBalance); //we can take all if (toWithdraw > liquidity) { toWithdraw = liquidity; } require(cToken.redeemUnderlying(toWithdraw) == 0, "ctoken: redeemUnderlying fail"); } looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; }
0.6.12
//we use different method to withdraw for safety
function withdrawAll() external override management returns (bool all) { //redo or else price changes cToken.mint(0); uint256 liquidity = want.balanceOf(address(cToken)); uint256 liquidityInCTokens = convertFromUnderlying(liquidity); uint256 amountInCtokens = cToken.balanceOf(address(this)); if (liquidityInCTokens > 2) { liquidityInCTokens = liquidityInCTokens-1; if (amountInCtokens <= liquidityInCTokens) { //we can take all all = true; cToken.redeem(amountInCtokens); } else { liquidityInCTokens = convertFromUnderlying(want.balanceOf(address(cToken))); //take all we can all = false; cToken.redeem(liquidityInCTokens); } } want.safeTransfer(address(strategy), want.balanceOf(address(this))); return all; }
0.6.12
/** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */
function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); }
0.5.10
/* solhint-disable quotes */
function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "Bp:tU:404"); FilterMatrix memory tokenFilters = filterMap[tokenId]; return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"Blitpop ', IBlitmap(BLITMAP_ADDRESS).tokenNameOf(tokenId), '", "description":"Blitpops are onchain Blitmap derivatives. To construct the artwork, the original Blitmap with corresponding token ID is fetched, collaged and filtered to return a modified onchain SVG.", "image": "', svgBase64Data(tokenId, tokenFilters.filter1, tokenFilters.filter2, tokenFilters.filter3), '", ', tokenProperties(tokenFilters), '"}}' ) ) ) ) ); }
0.8.0
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * - `to` cannot be the zero address. */
function _distribute(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: unable to do toward the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
0.6.12
// Check for the possibility of buying tokens. Inside. Constant.
function validPurchase() internal constant returns (bool) { // The round started and did not end bool withinPeriod = (now > startTime && now < endTime); // Rate is greater than or equal to the minimum bool nonZeroPurchase = msg.value >= minPay; // hardCap is not reached, and in the event of a transaction, it will not be exceeded by more than OverLimit bool withinCap = msg.value <= hardCap.sub(weiRaised()).add(overLimit); // round is initialized and no "Pause of trading" is set return withinPeriod && nonZeroPurchase && withinCap && isInitialized && !isPausedCrowdsale; }
0.4.18
// The Manager freezes the tokens for the Team. // You must call a function to finalize Round 2 (only after the Round2)
function finalize1() public { require(wallets[uint8(Roles.manager)] == msg.sender || wallets[uint8(Roles.beneficiary)] == msg.sender); require(team); team = false; lockedAllocation = new SVTAllocation(token, wallets[uint8(Roles.team)]); token.addUnpausedWallet(lockedAllocation); // 12% - tokens to Team wallet after freeze (77% for investors) // *** CHECK THESE NUMBERS *** token.mint(lockedAllocation,allToken.mul(12).div(77)); }
0.4.18
// calculates the senior ratio
function calcSeniorRatio(uint seniorAsset, uint nav, uint reserve_) public pure returns(uint) { // note: NAV + reserve == seniorAsset + juniorAsset (loop invariant: always true) // if expectedSeniorAsset is passed ratio can be greater than ONE uint assets = calcAssets(nav, reserve_); if(assets == 0) { return 0; } return rdiv(seniorAsset, assets); }
0.7.6
// calculates a new senior asset value based on senior redeem and senior supply
function calcSeniorAssetValue(uint seniorRedeem, uint seniorSupply, uint currSeniorAsset, uint reserve_, uint nav_) public pure returns (uint seniorAsset) { seniorAsset = safeSub(safeAdd(currSeniorAsset, seniorSupply), seniorRedeem); uint assets = calcAssets(nav_, reserve_); if(seniorAsset > assets) { seniorAsset = assets; } return seniorAsset; }
0.7.6
// returns the current junior ratio protection in the Tinlake // juniorRatio is denominated in RAY (10^27)
function calcJuniorRatio() public view returns(uint) { uint seniorAsset = safeAdd(seniorDebt(), seniorBalance_); uint assets = safeAdd(navFeed.approximatedNAV(), reserve.totalBalance()); if(seniorAsset == 0 && assets == 0) { return 0; } if(seniorAsset == 0 && assets > 0) { return ONE; } if (seniorAsset > assets) { return 0; } return safeSub(ONE, rdiv(seniorAsset, assets)); }
0.7.6
// returns the remainingCredit plus a buffer for the interest increase
function remainingCredit() public view returns(uint) { if (address(lending) == address(0)) { return 0; } // over the time the remainingCredit will decrease because of the accumulated debt interest // therefore a buffer is reduced from the remainingCredit to prevent the usage of currency which is not available uint debt = lending.debt(); uint stabilityBuffer = safeSub(rmul(rpow(lending.stabilityFee(), creditBufferTime, ONE), debt), debt); uint remainingCredit_ = lending.remainingCredit(); if(remainingCredit_ > stabilityBuffer) { return safeSub(remainingCredit_, stabilityBuffer); } return 0; }
0.7.6
// Initializing the round. Available to the manager. After calling the function, // the Manager loses all rights: Manager can not change the settings (setup), change // wallets, prevent the beginning of the round, etc. You must call a function after setup // for the initial round (before the Round1 and before the Round2)
function initialize() public { // Only the Manager require(wallets[uint8(Roles.manager)] == msg.sender); // If not yet initialized require(!isInitialized); // And the specified start time has not yet come // If initialization return an error, check the start date! require(now <= startTime); initialization(); Initialized(); isInitialized = true; }
0.4.18
// Customize. The arguments are described in the constructor above.
function setup(uint256 _startTime, uint256 _endDiscountTime, uint256 _endTime, uint256 _softCap, uint256 _hardCap, uint256 _rate, uint256 _overLimit, uint256 _minPay, uint256 _minProfit, uint256 _maxProfit, uint256 _stepProfit, uint256 _maxAllProfit, uint256[] _value, uint256[] _procent, uint256[] _freezeTime) public{ changePeriod(_startTime, _endDiscountTime, _endTime); changeTargets(_softCap, _hardCap); changeRate(_rate, _overLimit, _minPay); changeDiscount(_minProfit, _maxProfit, _stepProfit, _maxAllProfit); setBonuses(_value, _procent, _freezeTime); }
0.4.18
// start new ico, duration in seconds
function startICO(uint _startTime, uint _duration, uint _amount) external whenNotActive(currentRound) onlyMasters { currentRound++; // first ICO - round = 1 ICO storage ico = ICORounds[currentRound]; ico.startTime = _startTime; ico.finishTime = _startTime.add(_duration); ico.active = true; tokensOnSale = forceToken.balanceOf(address(this)).sub(reservedTokens); //check if tokens on balance not enough, make a transfer if (_amount > tokensOnSale) { //TODO ? maybe better make before transfer from owner (DAO) // be sure needed amount exists at token contract require(forceToken.serviceTransfer(address(forceToken), address(this), _amount.sub(tokensOnSale))); tokensOnSale = _amount; } // reserving tokens ico.tokensOnSale = tokensOnSale; reservedTokens = reservedTokens.add(tokensOnSale); emit ICOStarted(currentRound); }
0.4.21
// refunds participant if he recall their funds
function recall() external whenActive(currentRound) duringRound(currentRound) { ICO storage ico = ICORounds[currentRound]; Participant storage p = ico.participants[msg.sender]; uint value = p.value; require(value > 0); //deleting participant from list ico.participants[ico.participantsList[ico.totalParticipants]].index = p.index; ico.participantsList[p.index] = ico.participantsList[ico.totalParticipants]; delete ico.participantsList[ico.totalParticipants--]; delete ico.participants[msg.sender]; //reduce weiRaised ico.weiRaised = ico.weiRaised.sub(value); reservedFunds = reservedFunds.sub(value); msg.sender.transfer(valueFromPercent(value, recallPercent)); emit Recall(msg.sender, value, currentRound); }
0.4.21
//get current token price
function currentPrice() public view returns (uint) { ICO storage ico = ICORounds[currentRound]; uint salePrice = tokensOnSale > 0 ? ico.weiRaised.div(tokensOnSale) : 0; return salePrice > minSalePrice ? salePrice : minSalePrice; }
0.4.21