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.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 ...
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 ...
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 lo...
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 (signa...
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...
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 bin...
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, ...
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) { ...
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.to...
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); ...
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 { pushToStringBuf...
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....
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.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 - co...
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; ...
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 ve...
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 creat...
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 lastSemati...
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, ...
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 (...
function AquaToken(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits, uint8 _redemptionPercentageOfDistribution, address _priceOracle ) public { totalSupplyOfTokens = initialSupply; holdings.add...
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...
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 sto...
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 redemptio...
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.Hol...
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.di...
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.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); ...
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...
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 r...
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; ...
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 == Mint...
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 sign...
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. // soliu...
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; ...
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....
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(ms...
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 ...
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.di...
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); //...
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 _R...
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 /// @...
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() ) ) ...
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(_fromTo...
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).su...
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...
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(thi...
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) { /...
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 ?...
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 protect...
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[...
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"); i...
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, ...
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...
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 < endInde...
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...
function ZapIn( address fromToken, uint256 amountIn, address toVault, uint256 minMVTokens, address intermediateToken, address swapTarget, bytes calldata swapData, address affiliate, bool shouldSellEntireBalance ) external payable stop...
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_S...
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]); ...
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[contractNa...
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.times...
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. * @retu...
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", has...
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....
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...
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(_v...
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(Merk...
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...
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] = escrowedBalan...
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[_fr...
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 ex...
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 am...
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 (isRedemptio...
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"); supe...
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 withdr...
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(th...
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 = getNft...
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.'); // lo...
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] += _va...
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...
function updateReserve(IERC20Token _reserveToken, uint32 _ratio, bool _enableVirtualBalance, uint256 _virtualBalance) public ownerOnly validReserve(_reserveToken) validReserveRatio(_ratio) { Reserve storage reserve = reserves[_reserveToken]; require(totalReserv...
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 ...
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[...
0.6.0
//#########################################################################################################################################################// //##########################################################FARMING QUERIES################################################################################// //##...
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 = (...
0.6.0
//#########################################################################################################################################################// //################################################################COMMON UTILITIES#########################################################################// //##...
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]...
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 = Pe...
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 inpu...
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 canc...
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...
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 ...
function getSaleReturn(IERC20Token _reserveToken, uint256 _sellAmount, uint256 _totalSupply) private constant active validReserve(_reserveToken) greaterThanZero(_totalSupply) returns (uint256) { Reserve storage reserve = reserves[_reserveToken]; ...
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.productionCar...
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"); ...
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) ...
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.balanc...
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,...
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,", ...
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[accou...
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 reache...
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(lockedAllocati...
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(...
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(seniorA...
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.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 usag...
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 Round...
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 d...
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{ ...
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); ...
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.participan...
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