contract_name
stringlengths
1
61
file_path
stringlengths
5
50.4k
contract_address
stringlengths
42
42
language
stringclasses
1 value
class_name
stringlengths
1
61
class_code
stringlengths
4
330k
class_documentation
stringlengths
0
29.1k
class_documentation_type
stringclasses
6 values
func_name
stringlengths
0
62
func_code
stringlengths
1
303k
func_documentation
stringlengths
2
14.9k
func_documentation_type
stringclasses
4 values
compiler_version
stringlengths
15
42
license_type
stringclasses
14 values
swarm_source
stringlengths
0
71
meta
dict
__index_level_0__
int64
0
60.4k
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
hashToSVG
function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; }
/** * @dev Hash to SVG function */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 8613, 11767 ] }
4,400
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
hashToMetadata
function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); }
/** * @dev Hash to metadata function */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 11827, 12719 ] }
4,401
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
tokenURI
function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); }
/** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 12869, 14217 ] }
4,402
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
_tokenIdToHash
function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; }
/** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 14346, 14899 ] }
4,403
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
walletOfOwner
function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; }
/** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 15062, 15447 ] }
4,404
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
clearTraits
function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } }
/** * @dev Clears the traits. */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 16348, 16490 ] }
4,405
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
addTraitType
function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; }
/** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 16640, 17119 ] }
4,406
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
setTokenAddress
function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; }
/** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 17231, 17348 ] }
4,407
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
transferOwnership
function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; }
/** * @dev Transfers ownership * @param _newOwner The new owner */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 17441, 17546 ] }
4,408
NfToken
contracts/NfToken.sol
0x3146dd9c200421a9c7d7b67bd1b75ba3e2c15310
Solidity
NfToken
contract NfToken is ERC721Enumerable { using SafeMath for uint256; using Library for uint8; struct Trait { string traitName; string traitType; string pixels; uint256 pixelCount; } //Mappings mapping(uint256 => Trait[]) public traitTypes; mapping(string => bool) hashToMinted; mapping(uint256 => string) internal tokenIdToHash; //uint256s uint256 MAX_SUPPLY = 10000; uint256 MINTS_PER_TIER = 2000; uint256 SEED_NONCE = 0; uint256 MINT_START = 1633964400; uint256 MINT_DELAY = 43200; uint256 START_PRICE = 30000000000000000; uint256 PRICE_DIFF = 5000000000000000; //string arrays string[] LETTERS = [ "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ]; //uint arrays uint16[][8] TIERS; //address address tokenAddress; address _owner; constructor() ERC721("Moose", "MOOSE") { _owner = msg.sender; //Declare all the rarity tiers //Hat TIERS[0] = [4700, 3000, 1000, 1000, 200, 50, 50]; //Antlers TIERS[1] = [250, 500, 2500, 2250, 2250, 2250]; //Neck TIERS[2] = [4000, 2500, 1500, 1500, 500]; //Eyes TIERS[3] = [50, 100, 150, 200, 500, 500, 1000, 1500, 3000, 3000]; //Earrings TIERS[4] = [7000, 2000, 500, 200, 200, 50, 50]; //Mouth TIERS[5] = [1428, 1428, 1428, 1429, 1429, 1429, 1429]; //Character TIERS[6] = [1950, 1950, 1950, 1950, 1950, 200, 50]; //Accessory TIERS[7] = [9700, 200, 50, 50]; } /* __ __ _ _ _ ___ _ _ | \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___ | |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-< |_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/ |___/ */ /** * @dev Converts a digit from 0 - 10000 into its corresponding rarity based on the given rarity tier. * @param _randinput The input from 0 - 10000 to use for rarity gen. * @param _rarityTier The tier to use. */ function rarityGen(uint256 _randinput, uint8 _rarityTier) internal view returns (string memory) { uint16 currentLowerBound = 0; for (uint8 i = 0; i < TIERS[_rarityTier].length; i++) { uint16 thisPercentage = TIERS[_rarityTier][i]; if ( _randinput >= currentLowerBound && _randinput < currentLowerBound + thisPercentage ) return i.toString(); currentLowerBound = currentLowerBound + thisPercentage; } revert(); } /** * @dev Generates a 9 digit hash from a tokenId, address, and random number. * @param _t The token id to be used within the hash. * @param _a The address to be used within the hash. * @param _c The custom nonce to be used within the hash. */ function hash( uint256 _t, address _a, uint256 _c ) internal returns (string memory) { require(_c < 10); // This will generate a 9 character string. //The last 8 digits are random, the first is 0, due to the mouse not being burned. string memory currentHash = "0"; for (uint8 i = 0; i < 8; i++) { SEED_NONCE++; uint16 _randinput = uint16( uint256( keccak256( abi.encodePacked( block.timestamp, block.difficulty, _t, _a, _c, SEED_NONCE ) ) ) % 10000 ); currentHash = string( abi.encodePacked(currentHash, rarityGen(_randinput, i)) ); } if (hashToMinted[currentHash]) return hash(_t, _a, _c + 1); return currentHash; } /** * @dev Returns the current cost of minting. */ function currentTokenCost() public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply <= 2000) return 1000000000000000000; if (_totalSupply > 2000 && _totalSupply <= 4000) return 1000000000000000000; if (_totalSupply > 4000 && _totalSupply <= 6000) return 2000000000000000000; if (_totalSupply > 6000 && _totalSupply <= 8000) return 3000000000000000000; if (_totalSupply > 8000 && _totalSupply <= 10000) return 4000000000000000000; revert(); } /** * @dev Returns the current ETH price to mint */ function currentPrice() public view returns (uint256) { if(block.timestamp < MINT_START) { return START_PRICE; } uint256 _mintTiersComplete = (block.timestamp - MINT_START).div(MINT_DELAY); if(PRICE_DIFF * _mintTiersComplete >= START_PRICE) { return 0; } else { return START_PRICE - (PRICE_DIFF * _mintTiersComplete); } } /** * @dev Mint internal, this is to avoid code duplication. */ function mintInternal() internal { uint256 _totalSupply = totalSupply(); require(_totalSupply < MAX_SUPPLY); require(!Library.isContract(msg.sender)); uint256 thisTokenId = _totalSupply; tokenIdToHash[thisTokenId] = hash(thisTokenId, msg.sender, 0); hashToMinted[tokenIdToHash[thisTokenId]] = true; _mint(msg.sender, thisTokenId); } /** * @dev Mints new tokens. */ function mintNfToken(uint256 _times) public payable { uint256 _totalSupply = totalSupply(); uint256 _price = currentPrice(); require((_times > 0 && _times <= 5)); require(msg.value >= _times * _price); require(_totalSupply < MINTS_PER_TIER); require(block.timestamp >= MINT_START); for(uint256 i=0; i< _times; i++){ mintInternal(); } } /** * @dev Mint for token */ function mintWithToken() public { //Burn this much token IToken(tokenAddress).burnFrom(msg.sender, currentTokenCost()); return mintInternal(); } /** * @dev Burns and mints new. * @param _tokenId The token to burn. */ function burnForMint(uint256 _tokenId) public { require(ownerOf(_tokenId) == msg.sender); //Burn token _transfer( msg.sender, 0x000000000000000000000000000000000000dEaD, _tokenId ); mintInternal(); } /* ____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____ | \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/ | D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_ | / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ | | \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ | | . \| || | || | | | | || | \ | | | | || || | |\ | |__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Helper function to reduce pixel size within contract */ function letterToNumber(string memory _inputLetter) internal view returns (uint8) { for (uint8 i = 0; i < LETTERS.length; i++) { if ( keccak256(abi.encodePacked((LETTERS[i]))) == keccak256(abi.encodePacked((_inputLetter))) ) return (i); } revert(); } /** * @dev Hash to SVG function */ function hashToSVG(string memory _hash) public view returns (string memory) { string memory svgString; bool[24][24] memory placedPixels; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); for ( uint16 j = 0; j < traitTypes[i][thisTraitIndex].pixelCount; j++ ) { string memory thisPixel = Library.substring( traitTypes[i][thisTraitIndex].pixels, j * 4, j * 4 + 4 ); uint8 x = letterToNumber( Library.substring(thisPixel, 0, 1) ); uint8 y = letterToNumber( Library.substring(thisPixel, 1, 2) ); if (placedPixels[x][y]) continue; svgString = string( abi.encodePacked( svgString, "<rect class='c", Library.substring(thisPixel, 2, 4), "' x='", x.toString(), "' y='", y.toString(), "'/>" ) ); placedPixels[x][y] = true; } } svgString = string( abi.encodePacked( '<svg id="mouse-svg" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 24 24"> <rect class="bg" x="0" y="0" />', svgString, "<style>rect.bg{width:24px;height:24px;fill:#B6EAFF} rect{width:1px;height:1px;} #mouse-svg{shape-rendering: crispedges;} .c00{fill:#000000}.c01{fill:#B1ADAC}.c02{fill:#D7D7D7}.c03{fill:#FFA6A6}.c04{fill:#FFD4D5}.c05{fill:#B9AD95}.c06{fill:#E2D6BE}.c07{fill:#7F625A}.c08{fill:#A58F82}.c09{fill:#4B1E0B}.c10{fill:#6D2C10}.c11{fill:#D8D8D8}.c12{fill:#F5F5F5}.c13{fill:#433D4B}.c14{fill:#8D949C}.c15{fill:#05FF00}.c16{fill:#01C700}.c17{fill:#0B8F08}.c18{fill:#421C13}.c19{fill:#6B392A}.c20{fill:#A35E40}.c21{fill:#DCBD91}.c22{fill:#777777}.c23{fill:#848484}.c24{fill:#ABABAB}.c25{fill:#BABABA}.c26{fill:#C7C7C7}.c27{fill:#EAEAEA}.c28{fill:#0C76AA}.c29{fill:#0E97DB}.c30{fill:#10A4EC}.c31{fill:#13B0FF}.c32{fill:#2EB9FE}.c33{fill:#54CCFF}.c34{fill:#50C0F2}.c35{fill:#54CCFF}.c36{fill:#72DAFF}.c37{fill:#B6EAFF}.c38{fill:#FFFFFF}.c39{fill:#954546}.c40{fill:#0B87F7}.c41{fill:#FF2626}.c42{fill:#180F02}.c43{fill:#2B2319}.c44{fill:#FBDD4B}.c45{fill:#F5B923}.c46{fill:#CC8A18}.c47{fill:#3C2203}.c48{fill:#53320B}.c49{fill:#7B501D}.c50{fill:#FFE646}.c51{fill:#FFD627}.c52{fill:#F5B700}.c53{fill:#242424}.c54{fill:#4A4A4A}.c55{fill:#676767}.c56{fill:#F08306}.c57{fill:#FCA30E}.c58{fill:#FEBC0E}.c59{fill:#FBEC1C}.c60{fill:#14242F}.c61{fill:#B06837}.c62{fill:#8F4B0E}.c63{fill:#D88227}.c64{fill:#B06837}</style></svg>" ) ); return svgString; } /** * @dev Hash to metadata function */ function hashToMetadata(string memory _hash) public view returns (string memory) { string memory metadataString; for (uint8 i = 0; i < 9; i++) { uint8 thisTraitIndex = Library.parseInt( Library.substring(_hash, i, i + 1) ); metadataString = string( abi.encodePacked( metadataString, '{"trait_type":"', traitTypes[i][thisTraitIndex].traitType, '","value":"', traitTypes[i][thisTraitIndex].traitName, '"}' ) ); if (i != 8) metadataString = string(abi.encodePacked(metadataString, ",")); } return string(abi.encodePacked("[", metadataString, "]")); } /** * @dev Returns the SVG and metadata for a token Id * @param _tokenId The tokenId to return the SVG and metadata for. */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { require(_exists(_tokenId)); string memory tokenHash = _tokenIdToHash(_tokenId); return string( abi.encodePacked( "data:application/json;base64,", Library.encode( bytes( string( abi.encodePacked( '{"name": "NfToken #', Library.toString(_tokenId), '", "description": "This is a collection of 10,000 unique images. All the metadata and images are generated and stored 100% on-chain. No IPFS, no API.", "image": "data:image/svg+xml;base64,', Library.encode( bytes(hashToSVG(tokenHash)) ), '","attributes":', hashToMetadata(tokenHash), "}" ) ) ) ) ) ); } /** * @dev Returns a hash for a given tokenId * @param _tokenId The tokenId to return the hash for. */ function _tokenIdToHash(uint256 _tokenId) public view returns (string memory) { string memory tokenHash = tokenIdToHash[_tokenId]; //If this is a burned token, override the previous hash if (ownerOf(_tokenId) == 0x000000000000000000000000000000000000dEaD) { tokenHash = string( abi.encodePacked( "1", Library.substring(tokenHash, 1, 9) ) ); } return tokenHash; } /** * @dev Returns the wallet of a given wallet. Mainly for ease for frontend devs. * @param _wallet The wallet to get the tokens of. */ function walletOfOwner(address _wallet) public view returns (uint256[] memory) { uint256 tokenCount = balanceOf(_wallet); uint256[] memory tokensId = new uint256[](tokenCount); for (uint256 i; i < tokenCount; i++) { tokensId[i] = tokenOfOwnerByIndex(_wallet, i); } return tokensId; } /* ___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____ / \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/ | || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_ | O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ | | || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ | | | \ / | | || || . \ | | | || | \ | | | | || || | |\ | \___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___| */ /** * @dev Clears the traits. */ function clearTraits() public onlyOwner { for (uint256 i = 0; i < 9; i++) { delete traitTypes[i]; } } /** * @dev Add a trait type * @param _traitTypeIndex The trait type index * @param traits Array of traits to add */ function addTraitType(uint256 _traitTypeIndex, Trait[] memory traits) public onlyOwner { for (uint256 i = 0; i < traits.length; i++) { traitTypes[_traitTypeIndex].push( Trait( traits[i].traitName, traits[i].traitType, traits[i].pixels, traits[i].pixelCount ) ); } return; } /** * @dev Sets the ERC20 token address * @param _tokenAddress The token address */ function setTokenAddress(address _tokenAddress) public onlyOwner { tokenAddress = _tokenAddress; } /** * @dev Transfers ownership * @param _newOwner The new owner */ function transferOwnership(address _newOwner) public onlyOwner { _owner = _newOwner; } /** * @dev Withdraw ETH to owner */ function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } /** * @dev Modifier to only allow owner to call functions */ modifier onlyOwner() { require(_owner == msg.sender); _; } }
withdraw
function withdraw() public onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); }
/** * @dev Withdraw ETH to owner */
NatSpecMultiLine
v0.8.4+commit.c7e474f2
None
ipfs://95df3398ec2a2913850d0e25d77bea187e5bc19916b0df9ae930719f2d8b641f
{ "func_code_index": [ 17602, 17755 ] }
4,409
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
name
function name() public view returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 902, 990 ] }
4,410
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
symbol
function symbol() public view returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 1104, 1196 ] }
4,411
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decimals
function decimals() public view returns (uint8) { return _decimals; }
/** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 1829, 1917 ] }
4,412
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
totalSupply
function totalSupply() public view override returns (uint256) { return _totalSupply; }
/** * @dev See {IERC20-totalSupply}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 1977, 2082 ] }
4,413
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
balanceOf
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
/** * @dev See {IERC20-balanceOf}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 2140, 2264 ] }
4,414
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transfer
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; }
/** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 2472, 2652 ] }
4,415
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {IERC20-allowance}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 2710, 2866 ] }
4,416
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
approve
function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; }
/** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3008, 3182 ] }
4,417
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; }
/** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3651, 3977 ] }
4,418
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; }
/** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4381, 4604 ] }
4,419
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; }
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5102, 5376 ] }
4,420
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5861, 6405 ] }
4,421
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_mint
function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); }
/** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 6681, 7064 ] }
4,422
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_burn
function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); }
/** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 7391, 7814 ] }
4,423
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_approve
function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 8247, 8598 ] }
4,424
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_setupDecimals
function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; }
/** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 8925, 9020 ] }
4,425
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
ERC20
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
/** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */
NatSpecMultiLine
_beforeTokenTransfer
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
/** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 9618, 9715 ] }
4,426
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
SafeERC20
library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
/** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */
NatSpecMultiLine
safeApprove
function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); }
/** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 747, 1374 ] }
4,427
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
SafeERC20
library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
/** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */
NatSpecMultiLine
_callOptionalReturn
function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } }
/** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 2393, 3159 ] }
4,428
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
balance
function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); }
// Check the total underyling token balance to see if we should earn();
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3037, 3229 ] }
4,429
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setActive
function setActive(bool _isActive) external isGovernance { isActive = _isActive; }
// Sets whether deposits are accepted by the vault
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3288, 3389 ] }
4,430
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setMin
function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; }
// Set the minimum percentage of tokens that can be deposited to earn
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3468, 3596 ] }
4,431
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setGovernance
function setGovernance(address _governance) external isGovernance { governance = _governance; }
// Set a new governance address, can only be triggered by the old address
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3678, 3792 ] }
4,432
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setTreasury
function setTreasury(address _treasury) external isGovernance { treasury = _treasury; }
// Set a new treasury address, can only be triggered by the governance
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 3871, 3977 ] }
4,433
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setTimelock
function setTimelock(address _timelock) external isTimelock { timelock = _timelock; }
// Set the timelock address, can only be triggered by the old address
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4055, 4159 ] }
4,434
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setStrategy
function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; }
// Set a new strategy address, can only be triggered by the timelock
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4236, 4426 ] }
4,435
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setController
function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; }
// Set the controller address, can only be set once after deployment
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4503, 4676 ] }
4,436
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setBurnFee
function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; }
// Set the burn fee for multipliers
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4720, 4916 ] }
4,437
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setWithdrawalFee
function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; }
// Set withdrawal fee for the vault
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 4960, 5146 ] }
4,438
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
addMultiplier
function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; }
// Add a new multplier with the selected cost
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5200, 5376 ] }
4,439
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
setMultiplier
function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; }
// Set new cost for multiplier, can only be triggered by the timelock
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5454, 5579 ] }
4,440
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
available
function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); }
// Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5739, 5869 ] }
4,441
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
earn
function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); }
// Deposits collected underlying assets into the strategy and starts earning
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 5954, 6218 ] }
4,442
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
deposit
function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); }
// Deposits underlying assets from the user into the vault contract
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 6294, 7754 ] }
4,443
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
depositAll
function depositAll() external { deposit(token.balanceOf(msg.sender)); }
// Deposits all the funds of the user
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 7800, 7891 ] }
4,444
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
withdraw
function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); }
// No rebalance implementation for lower fees and faster swaps
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 7962, 10709 ] }
4,445
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
withdrawAll
function withdrawAll() external { withdraw(deposits[msg.sender]); }
// Withdraws all underlying assets belonging to the user
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 10774, 10860 ] }
4,446
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
purchaseMultiplier
function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); }
// Purchase a multiplier tier for the user
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 11273, 12261 ] }
4,447
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
distribute
function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } }
// Distribute the YVS tokens collected by the multiplier purchases
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 12336, 12686 ] }
4,448
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
salvage
function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); }
// Used to salvage any non-underlying assets to governance
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 12753, 13001 ] }
4,449
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
getMultiplier
function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; }
// Returns the current multiplier tier for the user
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 13061, 13166 ] }
4,450
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
getNextMultiplierCost
function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; }
// Returns the next multiplier tier cost for the user
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 13228, 13428 ] }
4,451
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
getCountOfMultipliers
function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; }
// Returns the total number of multipliers
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 13479, 13597 ] }
4,452
YvsVault
contracts/token/ERC20/ERC20.sol
0x0b1b5c66b519bf7b586fff0a7bace89227ac5eaf
Solidity
YvsVault
contract YvsVault is ERC20, ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 internal token; IERC20 internal yvs; // Underlying token address address public underlying; // Address of controller address public controller; // Minimum/maximum allowed to be invested uint256 public min = 9500; uint256 public constant max = 10000; // Burn fee on purchases uint256 public burnFee = 5000; uint256 public constant burnFeeMax = 7500; uint256 public constant burnFeeMin = 2500; uint256 public constant burnFeeBase = 10000; // Withdrawal fee uint256 public withdrawalFee = 25; uint256 public constant withdrawalFeeMax = 25; uint256 public constant withdrawalFeeBase = 10000; // Minimum deposit period uint256 public minDepositPeriod = 7 days; // Is the strategy active (inactive on deploy) bool public isActive = false; // Addresses address public governance; address public treasury; address public timelock; address public strategy; mapping(address => uint256) public depositBlocks; mapping(address => uint256) public deposits; mapping(address => uint256) public issued; mapping(address => uint256) public tiers; uint256[] public multiplierCosts; uint256 internal constant tierMultiplier = 5; uint256 internal constant tierBase = 100; uint256 public totalDeposited = 0; // EVENTS event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event SharesIssued(address indexed user, uint256 amount); event SharesPurged(address indexed user, uint256 amount); event ClaimRewards(address indexed user, uint256 amount); event MultiplierPurchased(address indexed user, uint256 tiers, uint256 totalCost); constructor(address _underlying, address _yvs, address _governance, address _treasury, address _timelock) public ERC20( string(abi.encodePacked("yvsie ", ERC20(_underlying).name())), string(abi.encodePacked("yvs", ERC20(_underlying).symbol())) ) { require(address(_underlying) != address(_yvs), "!underlying"); _setupDecimals(ERC20(_underlying).decimals()); token = IERC20(_underlying); yvs = IERC20(_yvs); underlying = _underlying; governance = _governance; treasury = _treasury; timelock = _timelock; // multiplier costs from tier 1 to 5 multiplierCosts.push(5000000000000000000); // 5 $yvs multiplierCosts.push(10000000000000000000); // 10 $yvs multiplierCosts.push(20000000000000000000); // 20 $yvs multiplierCosts.push(40000000000000000000); // 40 $yvs multiplierCosts.push(80000000000000000000); // 80 $yvs } // Check the total underyling token balance to see if we should earn(); function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IStrategy(strategy).balanceOf() ); } // Sets whether deposits are accepted by the vault function setActive(bool _isActive) external isGovernance { isActive = _isActive; } // Set the minimum percentage of tokens that can be deposited to earn function setMin(uint256 _min) external isGovernance { require(_min <= max, "min>max"); min = _min; } // Set a new governance address, can only be triggered by the old address function setGovernance(address _governance) external isGovernance { governance = _governance; } // Set a new treasury address, can only be triggered by the governance function setTreasury(address _treasury) external isGovernance { treasury = _treasury; } // Set the timelock address, can only be triggered by the old address function setTimelock(address _timelock) external isTimelock { timelock = _timelock; } // Set a new strategy address, can only be triggered by the timelock function setStrategy(address _strategy) external isTimelock { require(IStrategy(_strategy).underlying() == address(token), '!underlying'); strategy = _strategy; } // Set the controller address, can only be set once after deployment function setController(address _controller) external isGovernance { require(controller == address(0), "!controller"); controller = _controller; } // Set the burn fee for multipliers function setBurnFee(uint256 _burnFee) public isTimelock { require(_burnFee <= burnFeeMax, 'max'); require(_burnFee >= burnFeeMin, 'min'); burnFee = _burnFee; } // Set withdrawal fee for the vault function setWithdrawalFee(uint256 _withdrawalFee) external isTimelock { require(_withdrawalFee <= withdrawalFeeMax, "!max"); withdrawalFee = _withdrawalFee; } // Add a new multplier with the selected cost function addMultiplier(uint256 _cost) public isTimelock returns (uint256 index) { multiplierCosts.push(_cost); index = multiplierCosts.length - 1; } // Set new cost for multiplier, can only be triggered by the timelock function setMultiplier(uint256 index, uint256 _cost) public isTimelock { multiplierCosts[index] = _cost; } // Custom logic in here for how much of the underlying asset can be deposited // Sets the minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } // Deposits collected underlying assets into the strategy and starts earning function earn() public { require(isActive, 'earn: !active'); require(strategy != address(0), 'earn: !strategy'); uint256 _bal = available(); token.safeTransfer(strategy, _bal); IStrategy(strategy).deposit(); } // Deposits underlying assets from the user into the vault contract function deposit(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "deposit: !contract"); require(isActive, 'deposit: !vault'); require(strategy != address(0), 'deposit: !strategy'); uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens deposits[msg.sender] = deposits[msg.sender].add(_amount); totalDeposited = totalDeposited.add(_amount); uint256 shares = 0; if (totalSupply() == 0) { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = _amount.mul(userMultiplier).div(tierBase); } else { uint256 userMultiplier = tiers[msg.sender].mul(tierMultiplier).add(tierBase); // 5 %, 10 %, 15 %, 20 %, 25 % shares = (_amount.mul(userMultiplier).div(tierBase).mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); issued[msg.sender] = issued[msg.sender].add(shares); depositBlocks[msg.sender] = block.number; emit Deposit(msg.sender, _amount); emit SharesIssued(msg.sender, shares); } // Deposits all the funds of the user function depositAll() external { deposit(token.balanceOf(msg.sender)); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _amount) public nonReentrant { require(!address(msg.sender).isContract() && msg.sender == tx.origin, "withdraw: !no contract"); require(block.number >= depositBlocks[msg.sender].add(minDepositPeriod), 'withdraw: !minDepositPeriod'); require(_amount > 0, '!positive'); require(_amount <= deposits[msg.sender], '>deposit'); require(issued[msg.sender] > 0, '!deposit'); // Get the amount of user shares uint256 shares = issued[msg.sender]; // Calculate percentage of principal being withdrawn uint256 p = (_amount.mul(1e18).div(deposits[msg.sender])); // Calculate amount of shares to be burned uint256 r = shares.mul(p).div(1e18); // Make sure the user has the required amount in his balance require(balanceOf(msg.sender) >= r, "!shares"); // Burn the proportion of shares that are being withdrawn _burn(msg.sender, r); // Reduce the amount from user's issued amount issued[msg.sender] = issued[msg.sender].sub(r); // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 userRewards = 0; if (rewards > 0) { userRewards = (rewards.mul(shares)).div(totalSupply()); } // Receive the correct proportion of the rewards if (userRewards > 0) { userRewards = userRewards.mul(p).div(1e18); } // Calculate the withdrawal amount as _amount + user rewards uint256 withdrawAmount = _amount.add(userRewards); // Check balance uint256 b = token.balanceOf(address(this)); if (b < withdrawAmount) { uint256 _withdraw = withdrawAmount.sub(b); IStrategy(strategy).withdraw(_withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { withdrawAmount = b.add(_diff); } } // Remove the withdrawn principal from total and user deposits deposits[msg.sender] = deposits[msg.sender].sub(_amount); totalDeposited = totalDeposited.sub(_amount); // Calculate withdrawal fee and deduct from amount uint256 _withdrawalFee = _amount.mul(withdrawalFee).div(withdrawalFeeBase); token.safeTransfer(treasury, _withdrawalFee); token.safeTransfer(msg.sender, withdrawAmount.sub(_withdrawalFee)); // Emit events emit Withdraw(msg.sender, _amount); emit SharesPurged(msg.sender, r); emit ClaimRewards(msg.sender, userRewards); } // Withdraws all underlying assets belonging to the user function withdrawAll() external { withdraw(deposits[msg.sender]); } function pendingRewards(address account) external view returns (uint256 pending) { // Calculate amount of rewards the user has gained uint256 rewards = balance().sub(totalDeposited); uint256 shares = issued[account]; if (rewards > 0) { pending = (rewards.mul(shares)).div(totalSupply()); } } // Purchase a multiplier tier for the user function purchaseMultiplier(uint256 _tiers) external returns (uint256 newTier) { require(isActive, '!active'); require(strategy != address(0), '!strategy'); require(_tiers > 0, '!tiers'); uint256 multipliersLength = multiplierCosts.length; require(tiers[msg.sender].add(_tiers) <= multipliersLength, '!max'); uint256 totalCost = 0; uint256 lastMultiplier = tiers[msg.sender].add(_tiers); for (uint256 i = tiers[msg.sender]; i < multipliersLength; i++) { if (i == lastMultiplier) { break; } totalCost = totalCost.add(multiplierCosts[i]); } require(IERC20(yvs).balanceOf(msg.sender) >= totalCost, '!yvs'); yvs.safeTransferFrom(msg.sender, address(this), totalCost); newTier = tiers[msg.sender].add(_tiers); tiers[msg.sender] = newTier; emit MultiplierPurchased(msg.sender, _tiers, totalCost); } // Distribute the YVS tokens collected by the multiplier purchases function distribute() external restricted { uint256 b = yvs.balanceOf(address(this)); if (b > 0) { uint256 toBurn = b.mul(burnFee).div(burnFeeBase); uint256 leftover = b.sub(toBurn); Burnable(address(yvs)).burn(toBurn); yvs.safeTransfer(treasury, leftover); } } // Used to salvage any non-underlying assets to governance function salvage(address reserve, uint256 amount) external isGovernance { require(reserve != address(token), "!token"); require(reserve != address(yvs), "!yvs"); IERC20(reserve).safeTransfer(treasury, amount); } // Returns the current multiplier tier for the user function getMultiplier() external view returns (uint256) { return tiers[msg.sender]; } // Returns the next multiplier tier cost for the user function getNextMultiplierCost() external view returns (uint256) { require(tiers[msg.sender] < multiplierCosts.length, '!all'); return multiplierCosts[tiers[msg.sender]]; } // Returns the total number of multipliers function getCountOfMultipliers() external view returns (uint256) { return multiplierCosts.length; } // Returns the current ratio between earned assets and deposited assets function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); } // **** Modifiers **** // modifier restricted { require( (msg.sender == tx.origin && !address(msg.sender).isContract()) || msg.sender == governance || msg.sender == controller ); _; } modifier isTimelock { require( msg.sender == timelock, "!timelock" ); _; } modifier isGovernance { require( msg.sender == governance, "!governance" ); _; } }
getRatio
function getRatio() public view returns (uint256) { return (balance().sub(totalDeposited)).mul(1e18).div(totalSupply()); }
// Returns the current ratio between earned assets and deposited assets
LineComment
v0.6.12+commit.27d51765
MIT
ipfs://2e2461ba62cb785c7c9a5f5c0acb9c61592b82299e3ddb47f509184a3110c9a8
{ "func_code_index": [ 13677, 13818 ] }
4,453
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
add
function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; }
/** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 259, 445 ] }
4,454
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); }
/** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 723, 864 ] }
4,455
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
sub
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; }
/** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1162, 1359 ] }
4,456
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mul
function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; }
/** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1613, 2089 ] }
4,457
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); }
/** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 2560, 2697 ] }
4,458
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
div
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; }
/** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 3188, 3471 ] }
4,459
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 3931, 4066 ] }
4,460
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
SafeMath
library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } }
mod
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; }
/** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 4546, 4717 ] }
4,461
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "YouSwap: CALLER_IS_NOT_THE_OWNER"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
owner
function owner() public view returns (address) { return _owner; }
/** * @dev Returns the address of the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 447, 531 ] }
4,462
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "YouSwap: CALLER_IS_NOT_THE_OWNER"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
renounceOwnership
function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); }
/** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1087, 1240 ] }
4,463
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
Ownable
contract Ownable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == msg.sender, "YouSwap: CALLER_IS_NOT_THE_OWNER"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } }
transferOwnership
function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "YouSwap: NEW_OWNER_IS_THE_ZERO_ADDRESS"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
/** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1390, 1639 ] }
4,464
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
totalSupply
function totalSupply() external view returns (uint256);
/** * @dev Returns the amount of tokens in existence. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 95, 155 ] }
4,465
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
balanceOf
function balanceOf(address account) external view returns (uint256);
/** * @dev Returns the amount of tokens owned by `account`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 238, 311 ] }
4,466
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
transfer
function transfer(address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 535, 617 ] }
4,467
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
allowance
function allowance(address owner, address spender) external view returns (uint256);
/** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 896, 984 ] }
4,468
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
approve
function approve(address spender, uint256 amount) external returns (bool);
/** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1648, 1727 ] }
4,469
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
ITokenYou
interface ITokenYou { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); event MaxSupplyChanged(uint256 oldValue, uint256 newValue); function resetMaxSupply(uint256 newValue) external; function mint(address recipient, uint256 amount) external; function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 2040, 2142 ] }
4,470
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
name
function name() public pure returns (string memory) { return _name; }
/** * @dev Returns the name of the token. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 739, 827 ] }
4,471
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
symbol
function symbol() public pure returns (string memory) { return _symbol; }
/** * @dev Returns the symbol of the token, usually a shorter version of the * name. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 941, 1033 ] }
4,472
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
decimals
function decimals() public pure returns (uint8) { return _decimals; }
/** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1672, 1760 ] }
4,473
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
totalSupply
function totalSupply() public view override returns (uint256) { return _totalSupply; }
/** * @dev See {ITokenYou-totalSupply}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1823, 1928 ] }
4,474
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
maxSupply
function maxSupply() public view returns (uint256) { return _maxSupply; }
/** * @dev See {ITokenYou-maxSupply}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 1985, 2077 ] }
4,475
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
balanceOf
function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; }
/** * @dev See {ITokenYou-balanceOf}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 2324, 2449 ] }
4,476
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
transfer
function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; }
/** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 2660, 2838 ] }
4,477
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
allowance
function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; }
/** * @dev See {ITokenYou-allowance}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 2899, 3055 ] }
4,478
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
approve
function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; }
/** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 3200, 3364 ] }
4,479
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
transferFrom
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; }
/** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 3844, 4160 ] }
4,480
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
increaseAllowance
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; }
/** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 4567, 4778 ] }
4,481
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
decreaseAllowance
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; }
/** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 5279, 5543 ] }
4,482
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
_transfer
function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); }
/** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 6028, 6712 ] }
4,483
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
_burn
function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); }
/** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 7040, 7548 ] }
4,484
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
_approve
function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); }
/** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 7981, 8328 ] }
4,485
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
burn
function burn(uint256 amount) external override { _burn(msg.sender, amount); }
/** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 8442, 8539 ] }
4,486
TokenYou
TokenYou.sol
0x1d32916cfa6534d261ad53e2498ab95505bd2510
Solidity
TokenYou
contract TokenYou is Ownable, ITokenYou { using SafeMath for uint256; string private constant _name = 'YouSwap'; string private constant _symbol = 'YOU'; uint8 private constant _decimals = 6; uint256 private _totalSupply; uint256 private _transfers; uint256 private _holders; uint256 private _maxSupply; mapping(address => uint256) private _balanceOf; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => uint8) private _minters; constructor() public { _totalSupply = 0; _transfers = 0; _holders = 0; _maxSupply = 2 * 10 ** 14; } /** * @dev Returns the name of the token. */ function name() public pure returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public pure returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {ITokenYou-balanceOf} and {ITokenYou-transfer}. */ function decimals() public pure returns (uint8) { return _decimals; } /** * @dev See {ITokenYou-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {ITokenYou-maxSupply}. */ function maxSupply() public view returns (uint256) { return _maxSupply; } function transfers() public view returns (uint256) { return _transfers; } function holders() public view returns (uint256) { return _holders; } /** * @dev See {ITokenYou-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balanceOf[account]; } /** * @dev See {ITokenYou-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See {ITokenYou-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {ITokenYou-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(msg.sender, spender, amount); return true; } /** * @dev See {ITokenYou-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {ITokenYou-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "YouSwap: DECREASED_ALLOWANCE_BELOW_ZERO")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "YouSwap: TRANSFER_FROM_THE_ZERO_ADDRESS"); require(recipient != address(0), "YouSwap: TRANSFER_TO_THE_ZERO_ADDRESS"); require(amount > 0, "YouSwap: TRANSFER_ZERO_AMOUNT"); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[sender] = _balanceOf[sender].sub(amount, "YouSwap: TRANSFER_AMOUNT_EXCEEDS_BALANCE"); _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers ++; if (_balanceOf[sender] == 0) _holders--; emit Transfer(sender, recipient, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "YouSwap: BURN_FROM_THE_ZERO_ADDRESS"); require(_balanceOf[account] > 0, "YouSwap: INSUFFICIENT_FUNDS"); _balanceOf[account] = _balanceOf[account].sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_BALANCE"); if (_balanceOf[account] == 0) _holders --; _totalSupply = _totalSupply.sub(amount); _transfers++; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "YouSwap: APPROVE_FROM_THE_ZERO_ADDRESS"); require(spender != address(0), "YouSwap: APPROVE_TO_THE_ZERO_ADDRESS"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from the caller. * * See {TokenYou-_burn}. */ function burn(uint256 amount) external override { _burn(msg.sender, amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); } modifier isMinter() { require(_minters[msg.sender] == 1, "YouSwap: IS_NOT_A_MINTER"); _; } function isContract(address account) internal view returns (bool) { uint256 size; assembly {size := extcodesize(account)} return size > 0; } function mint(address recipient, uint256 amount) external override isMinter { require(_totalSupply.add(amount) <= _maxSupply, 'YouSwap: EXCEEDS_MAX_SUPPLY'); _totalSupply = _totalSupply.add(amount); if (_balanceOf[recipient] == 0) _holders++; _balanceOf[recipient] = _balanceOf[recipient].add(amount); _transfers++; emit Transfer(address(0), recipient, amount); } function addMinter(address account) external onlyOwner { require(isContract(account), "YouSwap: MUST_BE_A_CONTRACT_ADDRESS"); _minters[account] = 1; } function removeMinter(address account) external onlyOwner { _minters[account] = 0; } function resetMaxSupply(uint256 newValue) external override onlyOwner { require(newValue > _totalSupply && newValue < _maxSupply, 'YouSwap: NOT_ALLOWED'); emit MaxSupplyChanged(_maxSupply, newValue); _maxSupply = newValue; } }
burnFrom
function burnFrom(address account, uint256 amount) external override { uint256 decreasedAllowance = allowance(account, msg.sender).sub(amount, "YouSwap: BURN_AMOUNT_EXCEEDS_ALLOWANCE"); _approve(account, msg.sender, decreasedAllowance); _burn(account, amount); }
/** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {TokenYou-_burn} and {TokenYou-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
MIT
ipfs://36809148cac1cc85cf63caebc4099c1bf7a08c4d8fd9e521e905a4684ff22fc0
{ "func_code_index": [ 8859, 9160 ] }
4,487
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
owner
function owner() external view returns (address);
/** * @notice Returns the wallet owner. * @return The wallet owner address. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 118, 171 ] }
4,488
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
modules
function modules() external view returns (uint);
/** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 295, 347 ] }
4,489
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
setOwner
function setOwner(address _newOwner) external;
/** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 452, 502 ] }
4,490
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
authorised
function authorised(address _module) external view returns (bool);
/** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 704, 774 ] }
4,491
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
enabled
function enabled(bytes4 _sig) external view returns (address);
/** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 970, 1036 ] }
4,492
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
authoriseModule
function authoriseModule(address _module, bool _value) external;
/** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 1197, 1265 ] }
4,493
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/wallet/IWallet.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
IWallet
interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; }
/** * @title IWallet * @notice Interface for the BaseWallet */
NatSpecMultiLine
enableStaticCall
function enableStaticCall(address _module, bytes4 _method) external;
/** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 1479, 1551 ] }
4,494
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/infrastructure/base/Managed.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
Managed
contract Managed is Owned { // The managers mapping (address => bool) public managers; /** * @notice Throws if the sender is not a manager. */ modifier onlyManager { require(managers[msg.sender] == true, "M: Must be manager"); _; } event ManagerAdded(address indexed _manager); event ManagerRevoked(address indexed _manager); /** * @notice Adds a manager. * @param _manager The address of the manager. */ function addManager(address _manager) external onlyOwner { require(_manager != address(0), "M: Address must not be null"); if (managers[_manager] == false) { managers[_manager] = true; emit ManagerAdded(_manager); } } /** * @notice Revokes a manager. * @param _manager The address of the manager. */ function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); } }
/** * @title Managed * @notice Basic contract that defines a set of managers. Only the owner can add/remove managers. * @author Julien Niset - <[email protected]> */
NatSpecMultiLine
addManager
function addManager(address _manager) external onlyOwner { require(_manager != address(0), "M: Address must not be null"); if (managers[_manager] == false) { managers[_manager] = true; emit ManagerAdded(_manager); } }
/** * @notice Adds a manager. * @param _manager The address of the manager. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 479, 752 ] }
4,495
WalletFactory
/Users/Elena/Source/argent-contracts/contracts/infrastructure/base/Managed.sol
0x0d1ca6ec20b19cf30d7e32df62ff166a47ac5ecd
Solidity
Managed
contract Managed is Owned { // The managers mapping (address => bool) public managers; /** * @notice Throws if the sender is not a manager. */ modifier onlyManager { require(managers[msg.sender] == true, "M: Must be manager"); _; } event ManagerAdded(address indexed _manager); event ManagerRevoked(address indexed _manager); /** * @notice Adds a manager. * @param _manager The address of the manager. */ function addManager(address _manager) external onlyOwner { require(_manager != address(0), "M: Address must not be null"); if (managers[_manager] == false) { managers[_manager] = true; emit ManagerAdded(_manager); } } /** * @notice Revokes a manager. * @param _manager The address of the manager. */ function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); } }
/** * @title Managed * @notice Basic contract that defines a set of managers. Only the owner can add/remove managers. * @author Julien Niset - <[email protected]> */
NatSpecMultiLine
revokeManager
function revokeManager(address _manager) external onlyOwner { require(managers[_manager] == true, "M: Target must be an existing manager"); delete managers[_manager]; emit ManagerRevoked(_manager); }
/** * @notice Revokes a manager. * @param _manager The address of the manager. */
NatSpecMultiLine
v0.6.12+commit.27d51765
{ "func_code_index": [ 852, 1083 ] }
4,496
LIVEToken
LIVEToken.sol
0x90ecc785432a8ca60ae7a81eb34037a92a267a97
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
transfer
function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; }
/** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://9174d18f7247f20b68cbe22a3155b2429723e2ee5317637a65d39d153b64d8ac
{ "func_code_index": [ 268, 664 ] }
4,497
LIVEToken
LIVEToken.sol
0x90ecc785432a8ca60ae7a81eb34037a92a267a97
Solidity
BasicToken
contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } }
balanceOf
function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; }
/** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://9174d18f7247f20b68cbe22a3155b2429723e2ee5317637a65d39d153b64d8ac
{ "func_code_index": [ 870, 986 ] }
4,498
LIVEToken
LIVEToken.sol
0x90ecc785432a8ca60ae7a81eb34037a92a267a97
Solidity
StandardToken
contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { require((_value == 0) || (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } }
transferFrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; }
/** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */
NatSpecMultiLine
v0.4.26+commit.4563c3fc
None
bzzr://9174d18f7247f20b68cbe22a3155b2429723e2ee5317637a65d39d153b64d8ac
{ "func_code_index": [ 401, 858 ] }
4,499